Why isn't this jQuery selector finding anything? - javascript

I have a div inside a div. This inner div has a data attribute. I tried to apply the answer from this question to find the inner div, but am having no luck. What am I doing wrong?
var content = $('#mapElements').find('.mapMarker [data-depotid="b04b4184"]').data('depotguid');
$('#result').text(content);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='mapElements'>
<div class="mapMarker" data-depotid="b04b4184">This is the text from mapMarker, and if the depotID appears below this text the code works!</div>
</div>
<div id='result'></div>

Wrong Selector for targeting .mapMarker element. Use:
var content = $('#mapElements').find('.mapMarker[data-depotid="b04b4184"]').data('depotguid');
//^space not required here
You can also narrow down the selector for child element to:
var content = $('#mapElements').find('.mapMarker').data('depotguid');

Try this
$(" #mapElements > .mapMarker[data-depotid='b04b4184'] ");
or directly
$(".mapMarker [data-depotid='b04b4184']");

Related

Closest() in jQuery doesn't work when at the same level

Problem:
I want (after clicking on a button - this part is OK) to select the closest element with a class .my-textarea, but the using of prev() is not always possible, because the code is dynamic. Could you help?
Details:
I have this HTML code:
<div class="row">
<div class="label">Description:</div>
<textarea class="my-textarea" name="my-textarea" rows="8" cols="40"></textarea>
<button type="button" class="my-submit" name="my-submit">Save</button>
</div>
And my JS code (in on button with class "my-submit" click event) is:
var text = $(this).closest('.my-textarea').val();
But it's not working. I am getting undefined.
If I tried:-
var text = $(this).prev().val();
I will get the text of the text-area, but as I've mentioned, my code is dynamic and the order and number of elements will change. So, prev() is out of option.
Any idea how to make closest() work?
I always select parent and than search for child with class. That way your element can be placed virtually anywhere in parent.
$(this).parent().find('.my-textarea').val();
Need to Use siblings() instead of closest():-
$('.my-submit').click(function(e){
e.preventDefault();
var text = $(this).siblings('textarea').val();
console.log(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="label">Description:</div>
<textarea class="my-textarea" name="my-textarea" rows="8" cols="40"></textarea>
<button type="button" class="my-submit" name="my-submit">Save</button>
</div>
You need to refer it using class
closest will traverse up the DOM tree to look for the element, while in this case textarea is sibling of the button.
$('.my-submit').click(function(){
var text = $(this).siblings('.my-textarea').val();
alert(text)
})
DEMO

JQuery: adding attributes of Elements that appended

i tried to access the attribute of an element that appended to an element that it appended too.
".chat-private" appended too.
how can i do this?
this is my script code:
$('#users-list').on('click', '.chat-private', function () {
$("#dialog-area").append("<div class='dialog'><h4>Chat</h4><textarea cols='30' rows='10' id='chatarea'></textarea><input type='text' id='chattext'></div>");
var userid = $(this).attr("userid");
$('#dialog').attr('userid', userid);
});
and HTML:
<div id="users-list">
users:
</div>
<div id="dialogs-area">
</div>
Your div has a class dialog and in selector you are saying #dialog. You should say .dialog.
$('#dialog').attr('userid', userid);
DEMO
And you should avoid adding custom attributes to elements, use data-attributes inroduced in HTML5.
Add id's to your html strings. When you append the code, you can then reference them later by id to manipulate them. Just be careful - chicken before the egg and what not.
http://jsfiddle.net/qrggj2go/
<div id="test"/>
$("#test").append("<button id='test2'>Hi</button>");
$("#test2").click(function(){
$("#test2").hide();
});

How to append just before the end of the BODY tag using JQuery [duplicate]

I have this HTML:
<div class="region-list" id="region_North_America">
<strong>North America</strong>
</div>
and want to add more divs after the strong element to result:
<div class="region-list" id="region_North_America">
<strong>North America</strong>
<div> ... </div>
<div> ... </div>
<div> ... </div>
</div>
I am trying this:
var row_str = '<div>content here</div>';
$('#region_North_America div:last').html(row_str);
However, there is no change to the html. This is probably so since there is no div within the element selected.
I know that the js is making it to this code because I can print the content of row_str to the console.
So, how can I get to the end of that container element to add the new items?
Thx.
Try:
$("#region_North_America").append(row_str);
using append().
Or:
$("<div>content here</div>").appendTo("#region_North_America");
To create the element on the fly, and place it in the document.
Using the appendTo method.
Your code will just place html in the last div within #region_North_America. Use the append function.
$("div.region-list").append(row_str);

Get html content of a selector ( .html() ) with jQuery from a JavaScript variable that contains HTML

I have a javascript variable that contains a part of html code.
I need to get in this part of html code a div html content.
How can i do it ?
This is an example:
var code = '<style type="text/css">
#example{
border:1px;
font-size:20px;
}
</style>
<div id="ex"> Some Content </div>
<div id="ex2"> Some Content <span> Another Content</span></div>
<div id="my_code">This Is My Code.</div><div id="ex3> Etc Etc </div>';
I'd like get content of div "my_code" with Jquery .html();
How can i do it ?
Thanks
code variable it's just a string for your document. If you have parsed this HTML code inside the body then you can use $('#my_code'), otherwise it's still just a string so.. that's another story.
Check the other story here: http://jsfiddle.net/NSCQh/1/
I strongly suggest you have a look at jQuery's selector overview. They are the most important part of the jQuery magic, and without understanding them you'll get nowhere in the long run.
var html = $('#my_code').html()
or because that div containts text only
var txt = $('#my_code').text()
You've got a string, you need a DOM element. From that, you can get the jQuery object.
var el = document.createElement('div');
el.innerHTML = code;
console.log($(el));
pass the string to jquery and it works
var foo = '<div id="foo"> <span class="bar">fooBar</span> </div>';
var inside = $(foo).find('.bar').text();
alert(inside);
Create an ELEMENT, say p.
Use the following
$('<p>').append(code).find('div#my_code').html();
It create a p element, then append the content of variable code, then find div with id=my_code and select it's innerHTML.
Working model in the snippet.
var code = `<style type="text/css">
#example{
border:1px;
font-size:20px;
}
</style>
<div id="ex"> Some Content </div>
<div id="ex2"> Some Content <span> Another Content</span></div>
<div id="my_code">This Is My Code.</div><div id="ex3> Etc Etc </div>`;
var elm=$('<p>').append(code).find('div#my_code').html();
console.log(elm);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Very basic question about parent() and prev() in jQuery

I am handling a hyperlink's click event with a JavaScript function. I want to retrieve data from the hyperlink.
The page looks like this:
<div class="div1">
<div title="Title 1" class="div2">
<p class="p1"><a class="linkJs">The link in question</a></p>
</div>
</div>
<div class="div1">
<div title="Title 2" class="div2">
<p class="p1"><a class="linkJs">The link in question</a></p>
</div>
</div>
And the JavaScript something like this:
$(function() {
$('a.linkJs').click(function(){
value=$(this).parent().prev().text();
alert(value);
});
});
What I want to have is the value of the TITLE in the div2. By clicking the first link I get : Title 1. And by clicking on the 2nd: Title 2.
This must be very very basic but I just can't find my answer anywhere.
Thanks.
You want to use closest
var value = $(this).closest('div').attr('title');
Your problem is that the <p> tag is not a sibling to the <div> but a child, so you would have to do parent() twice - there's no need, though, as the closest function is a handy shortcut. Also, the text() function returns the pure text contents inside the tag, if you want the title attribute of the tag you need to use the attr function.
You can find it with the closest method:
$('a.linkJs').click(function(){
value=$(this).closest('div').attr('title');
alert(value);
});
try using the closest() method: http://api.jquery.com/closest/
Get the first ancestor element that
matches the selector, beginning at the
current element and progressing up
through the DOM tree.
$(function() {
$('a.linkJs').click(function(){
value=$(this).closest(".div2").attr("title");
alert(value);
});
});
var value = $(this).closest('.div2').attr('title');
Instead of using div, .div2 may be a more appropriate selector because there may be other div elements inside div.div2.
Not very pretty, but this should work too.
$(function() {
$('a.linkJs').click(function(){
value=$(this).parents()[1];
alert($(value).attr('title'));
});
});

Categories