find div where title equals something - javascript

<div id="subjectissueref"><div id="subjectissue">
<div title="myDivTitle" class="cbs-Line1Link ms-displayBlock"id="ctl00_PlaceHolderMain_g_9913c0d3_0331_4643_8d90_82268670a0f7_csr1_2lines_line1">
<b>Subject :</b> myDivTitle</div>
<div title="anotherDivTitle" class="cbs-Line1Link ms-displayBlock"id="ctl00_PlaceHolderMain_g_9913c0d3_0331_4643_8d90_82268670a0f7_csr1_2lines_line6"
><b>Issue :</b> anotherDivTitle</div></div>
<div title="53" class="cbs-Line1Link ms-displayBlock" id="ctl00_PlaceHolderMain_g_9913c0d3_0331_4643_8d90_82268670a0f7_csr1_2lines_line7" style="float: right;">
<b>Ref :</b> #53</div></div>
I have this bit of code, and I want to use javascript to find the element where title equals myDivTitle
$('#subjectissureref').find('div[title=myDivTitle]')

Try this:
$("div[title='myDivTitle']") // This will get div element

Try this:
elem = $("div[title='myDivTitle']");
or
elem = $("div").prop('title', 'myDivTitle');

FIDDLE
$("div").each(function(){
if($(this).prop('title')=="myDivTitle"){
alert( "This div has title as myDivTitle");
}
});

Alternatively you can use jQuery.filter(...) with a custom function to get some special selections e.g.:
jQuery(document).ready(function() {
jQuery('#subjectissueref .cbs-Line1Link').filter(function(index, elem) {
return jQuery(elem).attr('title') == 'anotherDivTitle';
}).css('background-color', 'green');
});
But in your case this is the shortest solution:
jQuery(document).ready(function() {
jQuery('#subjectissueref div[title="myDivTitle"]').css('background-color', 'red');
});
Try it out here: http://jsfiddle.net/algorhythm/1o1hjw61/

Related

Jquery find all elements with custom attribute begin with, get rest of it's name and it's value

Let's say we have element with custom attribute
... bind-html="varName" ...
I want to find all elements with attribute beginning with "bind-",
then get second part of it's name, which is unknown, in this case "html".
And at last get it's value "varName".
How do i achieved this with Jquery? I don't want to use second attribute to describe attibute to bind (like .. bind="varName" attr="html" ..)
You can use a loop through each object's attributes this.attributes and use the attribute's name and value properties.
Running example:
$("input").each(function() {
$.each(this.attributes, function() {
if (this.name.indexOf('bind-') == 0) {
console.log(this.name + ' has the value: ' + this.value);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<input bind-koby='hello'>
<input bind-douek='stack'>
<input will-not-show='yes'>
<input bind-hello='overflow'>
well that what you are looking for like
<div bind-html="varName">hi there i am </div>
well hi thats me
var namer = $(" *[attr*='bind']").text();
console.log(namer);
<div class="bindable" data-bind="html:varName1"></div>
<div class="bindable" data-bind="css:varName2"></div>
<div class="bindable" data-bind="js:varName3"></div>
<div class="bindable" data-bind="whatEver:varName4"></div>
(function(){
let bindables = $('.bindable');
bindables.each(function(){
let bindData = $(this).data('bind');
let bindDataArray = bindData.split(":");
console.log(bindDataArray);
});
}());
now u will get array with data u want
You can get all elements and their attributes which contain bind- by using jquery .properties and .indexOf() like following example.
// $("*") selects all elements in your html
$("*").each(function() {
$.each(this.attributes, function() {
// checks whether element has an attribute starts with "bind-" or not
if(this.specified && this.name.indexOf("bind-") !== -1) {
console.log("Attr Name: "+ this.name + " Attr Value: " + this.value)
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span bindNot-html="bindNot">element1</span>
<div bind-html="varName1">element2</div>
<a bind-html2="varName2">element3</a>
<div bind-html3="varName3">element4</div>
<span bindNot-html="bindNot">element5</span>

Get child element attribute using Jquery

I have a html structure. I want to get all controltypeid value in a function. I just try like
$('#firstDiv > a.[controltypeid]').each(function (i, val) {
$Control = $(val);
});
<div id="firstDiv">
<a id="1" controltypeid="1"></a>
<a id="2" controltypeid="2"></a>
<a id="3" controltypeid="3"></a>
</div>
but I can't get the value.Can any one help. Thanks in advance for help.
Done using jquery children selector.
Description :Get the children of each element in the set of matched elements.
Code :
$(document).ready(function(){
$("#firstDiv").children('a[controltypeid]').each(function(){
alert($(this).attr('controltypeid'))
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="firstDiv">
<a id="1" controltypeid="1"></a>
<a id="2" controltypeid="2"></a>
<a id="3" controltypeid="3"></a>
</div>
You could also use simply like this
$('#firstDiv a').each(function () {
alert($(this).attr('controltypeid'));
});
Try this if you need your controltypeid in a array:
var controltypeid = [];
$('#firstDiv > a[controltypeid]').each(function (i, v) {
controltypeid.push($(v).attr( "controltypeid" ));
});
console.log(controltypeid);
Did everyone forget about .map?
Example:
var controlTypeIds = $('#firstDiv').children().map(function() {
return $(this).attr('controltypeid');
}); // ['1', '2', '3']
Or, if you want to continue using your selector, remove the extra .. The . selector selects class, but having a attribute selector right after it .[...] makes no sense and is not syntactically correct.
var controlTypeIds = $('#firstDiv>a[controltypeid]').map(function() {
return $(this).attr('controltypeid');
}); // ['1', '2', '3']
a.[controltypeid] is wrong and is replaced by a[controltypeid]
secondly, use attr() to get the attribute value.
$('#firstDiv > a[controltypeid]').each(function () {
console.log( $( this ).attr( "controltypeid" ) );
});
if you just want to get all the values in a string
var controltypeids = [];
$('#firstDiv > a[controltypeid]').each(function () {
controltypeids.push( $( this ).attr( "controltypeid" ) );
console.log( $( this ).attr( "controltypeid" ) );
});
alert( controltypeids.join( "," ) );
You can get following way using JQuery. using attr
Make following changes in Jquery.
$('#firstDiv > a').each(function () {
alert($(this).attr('controltypeid'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="firstDiv">
<a id="1" controltypeid="1"></a>
<a id="2" controltypeid="2"></a>
<a id="3" controltypeid="3"></a>
</div>

Text replace javascript jquery

First of all Hello to everyone, and sorry for my English.
I would still take advantage of the expertise and availability of this community.
Yesterday i see a post(this) about string sostitution.
For simplicity, we remove the tables and try to look at the following code
<div id="find">
<div>(this match)</div>
<div>(this match)</div>
<div>some text1
<div></div>
<div>(this match)</div>
<div>some text2</div>
<div>some text3</div>
</div>
</div>
in this case if we want to find items that contain the word "match" and replace this word with "some other text" string, we can use one of these code snippet i found by reading other posts on this topic
$(document).ready(function(){
var elements = $('div');
for(var i = 0; i < elements.length; i++) {
var current = elements[i];
if(current.children.length === 0) {
var x=current.textContent
if (x.indexOf('match') > 0) {current.textContent='some other text'}
}
}
})
$(document).ready(function(){
$("#find div:contains('match'):not(:has(*))").each(function () {
var str=$(this).text('some other text')
})
})
$(document).ready(function(){
$("div").each(function(){
var str=''
var div = $(this).clone();
div.find("*").remove();
str=div.text();
if (str.indexOf('match') > 0) {
$(this).text('some other text')
}
})
})
However, if you edit the html in this way all snippets are wrong
<div id="find">(this match)
<div>(this match)
<div>(this match)</div>
</div>
<div>(this match)<div>aaaa</div></div>
<div>some text1
<div></div>
<div>(this match)</div>
<div>some text2</div>
<div>some text3</div>
</div>
</div>
I have found a solution to this problem but I think it's inelegant and overly verbose
$(document).ready(function(){
var len =$('#find div').length
for(i=1;i<len;i++){
$('div:eq('+i+')').contents().addClass('passed').filter(function () {
return $(this).text()==='(this match)' && $.trim(this.nodeValue).length
}).replaceWith('some other text');
}
for(i=0;i<len;i++){
var classx=$('div:eq('+i+')').attr('class')
if(classx===undefined){
var xx=$('div:eq('+i+')').contents()[0].nodeValue
if (xx.indexOf('match') > 0) {
$('div:eq('+i+')').contents()[0].nodeValue='some other text'
}
}
}
})
Please could someone direct me to a more efficient and elegant way to achieve the same result?
As always, thank you all in advance, any advice will be welcomed with pleasure.
I think what you want is here. If I understand what you want to do, a more "elegant" way of doing for the first snippet it could be:
$(document).ready(function(){
$('#find div').each(function () {
$(this).html($(this).html().replace('match', 'some other text'));
});
});
As for the second, this seems to work (as a caveat, it also works on the first snippet):
function findAllText (idToStartWith) {
$('#' + idToStartWith).html($('#' + idToStartWith).html().replace('match', 'some other text'));
while ($('#' + idToStartWith).text().indexOf('match') > 0) {
$('#' + idToStartWith).find('*').each(function () {
$(this).html($(this).html().replace('match', 'some other text'));
});
}
}

How to find the deepest child of a div with jquery

I'm trying to find the deepest element in the specified divwith jquery. But the code which used is producing the error TypeError: parent.children is not a function.
I found this code from this link
the code is :
function findDeepestChild(parent) {
var result = {depth: 0, element: parent};
parent.children().each( //Here I getting the error TypeError: parent.children is not a function
function(idx) {
var child = $(this);
var childResult = findDeepestChild(child);
if (childResult.depth + 1 > result.depth) {
result = {
depth: 1 + childResult.depth,
element: childResult.element};
}
}
);
return result;
}
---------------------------------------------------------------------------------------
$(document).on('keypress','#sendComment', function(e) {
if(e.keyCode==13){
var itemId=$('#findbefore').prev('.snew').attr('id');//
var item=findDeepestChild(itemId);
alert(item);
}
});
And my divs are :
<div id="S04" class="snew" style="display: block;">
<div class="author-image"></div>
<span>xyz shared the image xyz</span>
<div class="s-content">
<div class="s-message"></div>
<div class="shpicture">
<img class="SharedImage" width="100%" height="100%" data-shareid="1" data-alid="1" data-id="1" alt="xyz" src="data:image/jpeg;base64,">
</div>
</div>
</div>
<div class="SPcommentbox">
<div class="comment">
<div class="commenter-image"></div>
<div class="addcomment">
<input class="commentbox" type="text" placeholder="Write a comment...">
</div>
</div>
</div>
I need to find the img from these.
please anyone help me .... Thanks ...
To get the deepest nested elements, use
$("#" + parent).find("*").last().siblings().addBack()
http://jsfiddle.net/6ymUY/1/
you can then get the id data attribute with
item.data("id")
http://jsfiddle.net/6ymUY/2/
full code:
function findDeepestChild(parent) {
return $("#" + parent).find("*").last().siblings().addBack();
}
var item=findDeepestChild("S04");
console.log(item)
console.log(item.data("id"));
You're calling it with a string, but it's expecting a jQuery instance.
Instead of
var itemId=$('#findbefore').prev('.snew').attr('id');//
var item=findDeepestChild(itemId);
you probably want
var item=findDeepestChild($('#findbefore').prev('.snew'));
You are passing in itemId, which is the ID attribute of a given element. I think what you meant to pass was the element itself. Just remove the attr call, leaving this:
var item = findDeepestChild($("#findbefore").prev(".snew"));

How to compare an html entity with jQuery

I have the following html code:
<h3 id="headerid"><span onclick="expandCollapse('headerid')">⇑</span>Header title</h3>
I would like to toggle between up arrow and down arrow each time the user clicks the span tag.
function expandCollapse(id) {
var arrow = $("#"+id+" span").html(); // I have tried with .text() too
if(arrow == "⇓") {
$("#"+id+" span").html("⇑");
} else {
$("#"+id+" span").html("⇓");
}
}
My function is going always the else path. If I make a javacript:alert of arrow variable I am getting the html entity represented as an arrow. How can I tell jQuery to interpret the arrow variable as a string and not as html.
When the HTML is parsed, what JQuery sees in the DOM is a UPWARDS DOUBLE ARROW ("⇑"), not the entity reference. Thus, in your Javascript code you should test for "⇑" or "\u21d1". Also, you need to change what you're switching to:
function expandCollapse(id) {
var arrow = $("#"+id+" span").html();
if(arrow == "\u21d1") {
$("#"+id+" span").html("\u21d3");
} else {
$("#"+id+" span").html("\u21d1");
}
}
If you do an alert of arrow what does it return? Does it return the exact string that you're matching against? If you are getting the actual characters '⇓' and '⇑' you may have to match it against "\u21D1" and "\u21D3".
Also, you may want to try ⇑ and ⇓ since not all browsers support those entities.
Update: here's a fully working example:
http://jsbin.com/edogop/3/edit#html,live
window.expandCollapse = function (id) {
var $arrowSpan = $("#" + id + " span"),
arrowCharCode = $arrowSpan.text().charCodeAt(0);
// 8659 is the unicode value of the html entity
if (arrowCharCode === 8659) {
$arrowSpan.html("⇑");
} else {
$arrowSpan.html("⇓");
}
// one liner:
//$("#" + id + " span").html( ($("#" + id + " span").text().charCodeAt(0) === 8659) ? "⇑" : "⇓" );
};
Use a class to signal the current state of the span.
The html could look like this
<h3 id="headerId"><span class="upArrow">⇑</span>Header title</h3>
Then in the javascript you do
$( '.upArrow, .downArrow' ).click( function( span ) {
if ( span.hasClass( 'upArrow' ) )
span.text( "⇓" );
else
span.text( "⇑" );
span.toggleClass( 'upArrow' );
span.toggleClass( 'downArrow' );
} );
This may not be the best way, but it should work. Didnt test it tough
Check out the .toggle() effect.
Here is something similar i was playing with earlier.
HTML:
<div id="inplace">
<div id="myStatic">Hello World!</div>
<div id="myEdit" style="display: none">
<input id="myNewTxt" type="text" />
<input id="myOk" type="button" value="OK" />
<input id="myX" type="button" value="X" />
</div></div>
SCRIPT:
$("#myStatic").bind("click", function(){
$("#myNewTxt").val($("#myStatic").text());
$("#myStatic,#myEdit").toggle();
});
$("#myOk").click(function(){
$("#myStatic").text($("#myNewTxt").val());
$("#myStatic,#myEdit").toggle();
});
$("#myX").click(function(){
$("#myStatic,#myEdit").toggle();
});
Maybe you're not getting an exact match because the browser is lower-casing the entity or something. Try using a carat (^) and lower-case "v" just for testing.
Edited - My first theory was plain wrong.

Categories

Resources