Fetch specific element using custom attribute in jQuery












0















Below is a sample structure from which i'm trying to get the specific value of custom attribute



<div id="123"></div>
<div id="456"></div>
<div context="james"></div>


Below is how i'm trying to fetch, but it always returns false.



if ( $('div').attr('context') == 'james' ) {
alert("yes");
} else {
alert("no");
}









share|improve this question


















  • 1





    The first div does not have that attribute. attr() does not return an array, or find the element that has that attribute to get the value

    – Taplar
    Nov 14 '18 at 22:50











  • You could do $('div[context]').attr('context') but you should probably consider putting an id or class on it to avoid the attribute selector

    – Taplar
    Nov 14 '18 at 22:51






  • 1





    btw, your html is not valid unless your custom attribute starts with data- - so in this case it's best practice to use data-context="james". Also jQuery has specific support for data-* attributes: api.jquery.com/data

    – Robin Zigmond
    Nov 14 '18 at 22:59
















0















Below is a sample structure from which i'm trying to get the specific value of custom attribute



<div id="123"></div>
<div id="456"></div>
<div context="james"></div>


Below is how i'm trying to fetch, but it always returns false.



if ( $('div').attr('context') == 'james' ) {
alert("yes");
} else {
alert("no");
}









share|improve this question


















  • 1





    The first div does not have that attribute. attr() does not return an array, or find the element that has that attribute to get the value

    – Taplar
    Nov 14 '18 at 22:50











  • You could do $('div[context]').attr('context') but you should probably consider putting an id or class on it to avoid the attribute selector

    – Taplar
    Nov 14 '18 at 22:51






  • 1





    btw, your html is not valid unless your custom attribute starts with data- - so in this case it's best practice to use data-context="james". Also jQuery has specific support for data-* attributes: api.jquery.com/data

    – Robin Zigmond
    Nov 14 '18 at 22:59














0












0








0








Below is a sample structure from which i'm trying to get the specific value of custom attribute



<div id="123"></div>
<div id="456"></div>
<div context="james"></div>


Below is how i'm trying to fetch, but it always returns false.



if ( $('div').attr('context') == 'james' ) {
alert("yes");
} else {
alert("no");
}









share|improve this question














Below is a sample structure from which i'm trying to get the specific value of custom attribute



<div id="123"></div>
<div id="456"></div>
<div context="james"></div>


Below is how i'm trying to fetch, but it always returns false.



if ( $('div').attr('context') == 'james' ) {
alert("yes");
} else {
alert("no");
}






javascript jquery






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 14 '18 at 22:46









user2628187user2628187

11213




11213








  • 1





    The first div does not have that attribute. attr() does not return an array, or find the element that has that attribute to get the value

    – Taplar
    Nov 14 '18 at 22:50











  • You could do $('div[context]').attr('context') but you should probably consider putting an id or class on it to avoid the attribute selector

    – Taplar
    Nov 14 '18 at 22:51






  • 1





    btw, your html is not valid unless your custom attribute starts with data- - so in this case it's best practice to use data-context="james". Also jQuery has specific support for data-* attributes: api.jquery.com/data

    – Robin Zigmond
    Nov 14 '18 at 22:59














  • 1





    The first div does not have that attribute. attr() does not return an array, or find the element that has that attribute to get the value

    – Taplar
    Nov 14 '18 at 22:50











  • You could do $('div[context]').attr('context') but you should probably consider putting an id or class on it to avoid the attribute selector

    – Taplar
    Nov 14 '18 at 22:51






  • 1





    btw, your html is not valid unless your custom attribute starts with data- - so in this case it's best practice to use data-context="james". Also jQuery has specific support for data-* attributes: api.jquery.com/data

    – Robin Zigmond
    Nov 14 '18 at 22:59








1




1





The first div does not have that attribute. attr() does not return an array, or find the element that has that attribute to get the value

– Taplar
Nov 14 '18 at 22:50





The first div does not have that attribute. attr() does not return an array, or find the element that has that attribute to get the value

– Taplar
Nov 14 '18 at 22:50













You could do $('div[context]').attr('context') but you should probably consider putting an id or class on it to avoid the attribute selector

– Taplar
Nov 14 '18 at 22:51





You could do $('div[context]').attr('context') but you should probably consider putting an id or class on it to avoid the attribute selector

– Taplar
Nov 14 '18 at 22:51




1




1





btw, your html is not valid unless your custom attribute starts with data- - so in this case it's best practice to use data-context="james". Also jQuery has specific support for data-* attributes: api.jquery.com/data

– Robin Zigmond
Nov 14 '18 at 22:59





btw, your html is not valid unless your custom attribute starts with data- - so in this case it's best practice to use data-context="james". Also jQuery has specific support for data-* attributes: api.jquery.com/data

– Robin Zigmond
Nov 14 '18 at 22:59












2 Answers
2






active

oldest

votes


















3














The call to $('div').attr('context') will only grab the first div found in the DOM and check it's value. Since it doesn't have that attribute you get false. Instead you will want to iterate over all your div's and check each one. For example:



var found = false;
$('div').each(function( ) {
if($(this).attr('context') === 'james') found = true;
});
if(found) alert("yes");
else alert("no")


You could also use .filter:



if( $('div').filter(function(){ return $(this).attr('context') === 'james' }).length )
alert("yes");
else
alert("no");


Note: If you used data-context="james" you would use the .data() method rather than .attr().






share|improve this answer





















  • 1





    Awesome answer, I love the alternative that uses .filter() because it's an easy one-liner :) might want to suggest OP to use strict equality === instead.

    – Terry
    Nov 14 '18 at 23:01











  • @Terry Good point, changed to ===.

    – Spencer Wieczorek
    Nov 14 '18 at 23:02



















0














Simply let jQuery do the filtering for you. Also, this can be done with plain old vanilla javascript pretty easily:






// Select by attribute
var theDiv = $("div[context='james']");

// If we have something here...
if(theDiv.length){
console.log(theDiv.text() );
} else {
console.log("Nope, not found.");
}

// We can use this same selector with plain javascript...
let theSameDiv = document.querySelector("div[context='james']");

// In this event, however, we access the text differently.
if(theSameDiv){
console.log("Found without jQuery!", theSameDiv.textContent);
} else {
console.log("Rats...");
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="123">the first div</div>
<div id="456">div the second</div>
<div context="james">I'm 'Enry the Eighth, I Am!</div>








share|improve this answer


























  • The issue here is, while you can do this, attribute selectors effectively perform a DOM scan. The browser does not index elements by all their attributes, so when you search by an attribute, it literally has to step though every single node in the context to see if it matches. This is why for performance reasons it is better to use a tagName/class/id selector, or if you are forced to use an attribute only selector, to scope down the context upon which you are performing it on so as to reduce the number of nodes it has to evaluate against.

    – Taplar
    Nov 14 '18 at 23:20











  • And you're absolutely right. I was simplifying, as I had a very limited number of nodes. Changed the code to include the div tagName, in order to limit that number of nodes. Very good point, and well worth noting. Thank you!

    – Snowmonkey
    Nov 14 '18 at 23:28











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53309868%2ffetch-specific-element-using-custom-attribute-in-jquery%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









3














The call to $('div').attr('context') will only grab the first div found in the DOM and check it's value. Since it doesn't have that attribute you get false. Instead you will want to iterate over all your div's and check each one. For example:



var found = false;
$('div').each(function( ) {
if($(this).attr('context') === 'james') found = true;
});
if(found) alert("yes");
else alert("no")


You could also use .filter:



if( $('div').filter(function(){ return $(this).attr('context') === 'james' }).length )
alert("yes");
else
alert("no");


Note: If you used data-context="james" you would use the .data() method rather than .attr().






share|improve this answer





















  • 1





    Awesome answer, I love the alternative that uses .filter() because it's an easy one-liner :) might want to suggest OP to use strict equality === instead.

    – Terry
    Nov 14 '18 at 23:01











  • @Terry Good point, changed to ===.

    – Spencer Wieczorek
    Nov 14 '18 at 23:02
















3














The call to $('div').attr('context') will only grab the first div found in the DOM and check it's value. Since it doesn't have that attribute you get false. Instead you will want to iterate over all your div's and check each one. For example:



var found = false;
$('div').each(function( ) {
if($(this).attr('context') === 'james') found = true;
});
if(found) alert("yes");
else alert("no")


You could also use .filter:



if( $('div').filter(function(){ return $(this).attr('context') === 'james' }).length )
alert("yes");
else
alert("no");


Note: If you used data-context="james" you would use the .data() method rather than .attr().






share|improve this answer





















  • 1





    Awesome answer, I love the alternative that uses .filter() because it's an easy one-liner :) might want to suggest OP to use strict equality === instead.

    – Terry
    Nov 14 '18 at 23:01











  • @Terry Good point, changed to ===.

    – Spencer Wieczorek
    Nov 14 '18 at 23:02














3












3








3







The call to $('div').attr('context') will only grab the first div found in the DOM and check it's value. Since it doesn't have that attribute you get false. Instead you will want to iterate over all your div's and check each one. For example:



var found = false;
$('div').each(function( ) {
if($(this).attr('context') === 'james') found = true;
});
if(found) alert("yes");
else alert("no")


You could also use .filter:



if( $('div').filter(function(){ return $(this).attr('context') === 'james' }).length )
alert("yes");
else
alert("no");


Note: If you used data-context="james" you would use the .data() method rather than .attr().






share|improve this answer















The call to $('div').attr('context') will only grab the first div found in the DOM and check it's value. Since it doesn't have that attribute you get false. Instead you will want to iterate over all your div's and check each one. For example:



var found = false;
$('div').each(function( ) {
if($(this).attr('context') === 'james') found = true;
});
if(found) alert("yes");
else alert("no")


You could also use .filter:



if( $('div').filter(function(){ return $(this).attr('context') === 'james' }).length )
alert("yes");
else
alert("no");


Note: If you used data-context="james" you would use the .data() method rather than .attr().







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 14 '18 at 23:02

























answered Nov 14 '18 at 22:58









Spencer WieczorekSpencer Wieczorek

17.5k43345




17.5k43345








  • 1





    Awesome answer, I love the alternative that uses .filter() because it's an easy one-liner :) might want to suggest OP to use strict equality === instead.

    – Terry
    Nov 14 '18 at 23:01











  • @Terry Good point, changed to ===.

    – Spencer Wieczorek
    Nov 14 '18 at 23:02














  • 1





    Awesome answer, I love the alternative that uses .filter() because it's an easy one-liner :) might want to suggest OP to use strict equality === instead.

    – Terry
    Nov 14 '18 at 23:01











  • @Terry Good point, changed to ===.

    – Spencer Wieczorek
    Nov 14 '18 at 23:02








1




1





Awesome answer, I love the alternative that uses .filter() because it's an easy one-liner :) might want to suggest OP to use strict equality === instead.

– Terry
Nov 14 '18 at 23:01





Awesome answer, I love the alternative that uses .filter() because it's an easy one-liner :) might want to suggest OP to use strict equality === instead.

– Terry
Nov 14 '18 at 23:01













@Terry Good point, changed to ===.

– Spencer Wieczorek
Nov 14 '18 at 23:02





@Terry Good point, changed to ===.

– Spencer Wieczorek
Nov 14 '18 at 23:02













0














Simply let jQuery do the filtering for you. Also, this can be done with plain old vanilla javascript pretty easily:






// Select by attribute
var theDiv = $("div[context='james']");

// If we have something here...
if(theDiv.length){
console.log(theDiv.text() );
} else {
console.log("Nope, not found.");
}

// We can use this same selector with plain javascript...
let theSameDiv = document.querySelector("div[context='james']");

// In this event, however, we access the text differently.
if(theSameDiv){
console.log("Found without jQuery!", theSameDiv.textContent);
} else {
console.log("Rats...");
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="123">the first div</div>
<div id="456">div the second</div>
<div context="james">I'm 'Enry the Eighth, I Am!</div>








share|improve this answer


























  • The issue here is, while you can do this, attribute selectors effectively perform a DOM scan. The browser does not index elements by all their attributes, so when you search by an attribute, it literally has to step though every single node in the context to see if it matches. This is why for performance reasons it is better to use a tagName/class/id selector, or if you are forced to use an attribute only selector, to scope down the context upon which you are performing it on so as to reduce the number of nodes it has to evaluate against.

    – Taplar
    Nov 14 '18 at 23:20











  • And you're absolutely right. I was simplifying, as I had a very limited number of nodes. Changed the code to include the div tagName, in order to limit that number of nodes. Very good point, and well worth noting. Thank you!

    – Snowmonkey
    Nov 14 '18 at 23:28
















0














Simply let jQuery do the filtering for you. Also, this can be done with plain old vanilla javascript pretty easily:






// Select by attribute
var theDiv = $("div[context='james']");

// If we have something here...
if(theDiv.length){
console.log(theDiv.text() );
} else {
console.log("Nope, not found.");
}

// We can use this same selector with plain javascript...
let theSameDiv = document.querySelector("div[context='james']");

// In this event, however, we access the text differently.
if(theSameDiv){
console.log("Found without jQuery!", theSameDiv.textContent);
} else {
console.log("Rats...");
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="123">the first div</div>
<div id="456">div the second</div>
<div context="james">I'm 'Enry the Eighth, I Am!</div>








share|improve this answer


























  • The issue here is, while you can do this, attribute selectors effectively perform a DOM scan. The browser does not index elements by all their attributes, so when you search by an attribute, it literally has to step though every single node in the context to see if it matches. This is why for performance reasons it is better to use a tagName/class/id selector, or if you are forced to use an attribute only selector, to scope down the context upon which you are performing it on so as to reduce the number of nodes it has to evaluate against.

    – Taplar
    Nov 14 '18 at 23:20











  • And you're absolutely right. I was simplifying, as I had a very limited number of nodes. Changed the code to include the div tagName, in order to limit that number of nodes. Very good point, and well worth noting. Thank you!

    – Snowmonkey
    Nov 14 '18 at 23:28














0












0








0







Simply let jQuery do the filtering for you. Also, this can be done with plain old vanilla javascript pretty easily:






// Select by attribute
var theDiv = $("div[context='james']");

// If we have something here...
if(theDiv.length){
console.log(theDiv.text() );
} else {
console.log("Nope, not found.");
}

// We can use this same selector with plain javascript...
let theSameDiv = document.querySelector("div[context='james']");

// In this event, however, we access the text differently.
if(theSameDiv){
console.log("Found without jQuery!", theSameDiv.textContent);
} else {
console.log("Rats...");
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="123">the first div</div>
<div id="456">div the second</div>
<div context="james">I'm 'Enry the Eighth, I Am!</div>








share|improve this answer















Simply let jQuery do the filtering for you. Also, this can be done with plain old vanilla javascript pretty easily:






// Select by attribute
var theDiv = $("div[context='james']");

// If we have something here...
if(theDiv.length){
console.log(theDiv.text() );
} else {
console.log("Nope, not found.");
}

// We can use this same selector with plain javascript...
let theSameDiv = document.querySelector("div[context='james']");

// In this event, however, we access the text differently.
if(theSameDiv){
console.log("Found without jQuery!", theSameDiv.textContent);
} else {
console.log("Rats...");
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="123">the first div</div>
<div id="456">div the second</div>
<div context="james">I'm 'Enry the Eighth, I Am!</div>








// Select by attribute
var theDiv = $("div[context='james']");

// If we have something here...
if(theDiv.length){
console.log(theDiv.text() );
} else {
console.log("Nope, not found.");
}

// We can use this same selector with plain javascript...
let theSameDiv = document.querySelector("div[context='james']");

// In this event, however, we access the text differently.
if(theSameDiv){
console.log("Found without jQuery!", theSameDiv.textContent);
} else {
console.log("Rats...");
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="123">the first div</div>
<div id="456">div the second</div>
<div context="james">I'm 'Enry the Eighth, I Am!</div>





// Select by attribute
var theDiv = $("div[context='james']");

// If we have something here...
if(theDiv.length){
console.log(theDiv.text() );
} else {
console.log("Nope, not found.");
}

// We can use this same selector with plain javascript...
let theSameDiv = document.querySelector("div[context='james']");

// In this event, however, we access the text differently.
if(theSameDiv){
console.log("Found without jQuery!", theSameDiv.textContent);
} else {
console.log("Rats...");
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="123">the first div</div>
<div id="456">div the second</div>
<div context="james">I'm 'Enry the Eighth, I Am!</div>






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 14 '18 at 23:27

























answered Nov 14 '18 at 23:14









SnowmonkeySnowmonkey

3,07211012




3,07211012













  • The issue here is, while you can do this, attribute selectors effectively perform a DOM scan. The browser does not index elements by all their attributes, so when you search by an attribute, it literally has to step though every single node in the context to see if it matches. This is why for performance reasons it is better to use a tagName/class/id selector, or if you are forced to use an attribute only selector, to scope down the context upon which you are performing it on so as to reduce the number of nodes it has to evaluate against.

    – Taplar
    Nov 14 '18 at 23:20











  • And you're absolutely right. I was simplifying, as I had a very limited number of nodes. Changed the code to include the div tagName, in order to limit that number of nodes. Very good point, and well worth noting. Thank you!

    – Snowmonkey
    Nov 14 '18 at 23:28



















  • The issue here is, while you can do this, attribute selectors effectively perform a DOM scan. The browser does not index elements by all their attributes, so when you search by an attribute, it literally has to step though every single node in the context to see if it matches. This is why for performance reasons it is better to use a tagName/class/id selector, or if you are forced to use an attribute only selector, to scope down the context upon which you are performing it on so as to reduce the number of nodes it has to evaluate against.

    – Taplar
    Nov 14 '18 at 23:20











  • And you're absolutely right. I was simplifying, as I had a very limited number of nodes. Changed the code to include the div tagName, in order to limit that number of nodes. Very good point, and well worth noting. Thank you!

    – Snowmonkey
    Nov 14 '18 at 23:28

















The issue here is, while you can do this, attribute selectors effectively perform a DOM scan. The browser does not index elements by all their attributes, so when you search by an attribute, it literally has to step though every single node in the context to see if it matches. This is why for performance reasons it is better to use a tagName/class/id selector, or if you are forced to use an attribute only selector, to scope down the context upon which you are performing it on so as to reduce the number of nodes it has to evaluate against.

– Taplar
Nov 14 '18 at 23:20





The issue here is, while you can do this, attribute selectors effectively perform a DOM scan. The browser does not index elements by all their attributes, so when you search by an attribute, it literally has to step though every single node in the context to see if it matches. This is why for performance reasons it is better to use a tagName/class/id selector, or if you are forced to use an attribute only selector, to scope down the context upon which you are performing it on so as to reduce the number of nodes it has to evaluate against.

– Taplar
Nov 14 '18 at 23:20













And you're absolutely right. I was simplifying, as I had a very limited number of nodes. Changed the code to include the div tagName, in order to limit that number of nodes. Very good point, and well worth noting. Thank you!

– Snowmonkey
Nov 14 '18 at 23:28





And you're absolutely right. I was simplifying, as I had a very limited number of nodes. Changed the code to include the div tagName, in order to limit that number of nodes. Very good point, and well worth noting. Thank you!

– Snowmonkey
Nov 14 '18 at 23:28


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53309868%2ffetch-specific-element-using-custom-attribute-in-jquery%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Florida Star v. B. J. F.

Danny Elfman

Retrieve a Users Dashboard in Tumblr with R and TumblR. Oauth Issues