can't get correct results from this jquery object - javascript

I have the following bit of javascript and have tried a number of different ways to get the text from the div with the class dvservicestitle, and any li tags in the div with the dvservicescontent class. Neither work and I'm not sure why. Anyone have an idea what's wrong with this code?
if (html == "") html = "<div class='dvservicestitle'>Our Services</div><div class='dvservicescontent'><ul></ul></div>";
var title = $(html).find(".dvservicestitle");
var elements = $("dvservicescontent li", $(html));

The reason is because the find() method finds children nodes on the current node. Your HTML variable IS the div that you are looking for so the find() method doesn't find it. You need to wrap it in another container.
html = "<div class='dvservicestitle'>Our Services</div><div class='dvservicescontent'><ul></ul></div>";
$(html).find(".dvservicestitle")
>> []
$(html).hasClass("dvservicestitle")
>> true
html = "<div><div class='dvservicestitle'>Our Services</div><div class='dvservicescontent'><ul></ul></div></div>"
$(html).find(".dvservicestitle")
>> [<div class=​"dvservicestitle">​Our Services​</div>​]

you can use:
var title = $(".dvservicestitle").text();
var elements = $(".dvservicescontent li").text();

.find searches descendants which you don't have. The div to search exists at top level, so it is one of the elements in the jQuery object.
Use .filter to filter the correct element:
$(html).filter(".dvservicestile").text();

var title = $(html).find(".dvservicestitle").html();
var elements = $(html).find('.dvservicescontent ul').children();

Related

displaying specific text on tumblr [duplicate]

It looks like JQuery does the search in the current document when using a selector.
How to search for an element only inside a div element?
jQuery selectors work very much like CSS selectors, which you may be more familiar with.
First, select the div, and then descend from that:
$('#my-div').find('some-selector').
or build your selector to match children of the element in question:
$('#my-div some-selector')
Old question, but everyone seems to have missed the scoped jQuery selector (using the scope you desired, i.e. your div selector, as the second parameter)
e.g. use
var $matches = $('.adiv', '#mydiv');
This is a shorter equivalent of:
var $matches = $('#mydiv').find('.adiv');
var elems = jQuery(".foo", jQuery("#divYourWantToLimitTo") ); //BAD
//or
var elems = jQuery("#divYourWantToLimitTo .foo"); //Better
//or
var elems = jQuery("#divYourWantToLimitTo").find(".foo"); //BEST
jQuery provides several ways to search for specific elements:
$("#your_div").find(".your_things"); //Find everything inside
//-or-
$("#your_div").filter(".your_things"); //Find only the top level
//-or-
$("#your_div .your_things"); //Easiest
var elements = $('div ' + yourSearch);
$('div-selector').find('the selector-you-are-looking-for');

Best way to search for elements in innerHTML

I'm using innerHTML to get the inner HTML of an li element that is clicked. I would then like to search that HTML for some paragraph tags and find their value, is there a good way to do that? I can't rewrite any of the list's HTML, that's being generated elsewhere in the project but I do know the class names used for the tags. jQuery answers are fine.
The best way to 'search' the HTML is to use the DOM. Note that if the container element in which you want to search exists in your DOM already, you do not need to contruct a new dummy element and can just retrieve this parent node and use the same approach.
var el = document.createElement('div'),
someHtmlToSearch = '<div><p>test content in p</p></div>',
pContent;
el.innerHTML = someHtmlToSearch;
pContent = el.querySelector('p').innerHTML; //search for the first p tag
console.log(pContent); //test content in p
Using jQuery:
// Attach onclick listener to li items of interest
$("your-li-selector").on('click', function () {
// Select all p tags within the clicked element
var pTags = $('p', this);
// Iterate over all p tags
pTags.each(function () {
// Do search actions with `this.innerHtml` or `$(this).html()`
});
});
$("li").click(function(){
var myPrag=this.innerHTML.find("p");
});
Then use myParag
P.s. not tested

Inserting variable into array item

I have an array of elements from my webpage which I am trying to then insert some html, stored as a variable into a matching array item. For example
<div class="play">
<div>
<p>Item to be inserted after this p tag</p>
</div>
</div>
var elements = $('.play');
//elements length = 4;
var item = '<p>HTML to be inserted</p>'
$(item).appendTo(elements[1]);
In the above code I am trying to insert 'item' into the second value in the array within the child div shown in the html, however I am unsure how to insert it into the child div. At present this inserts 'item' after the parent html tag containing .play.
Any help would be greatly appreciated.
Note that elements isn't an array, it's a jQuery object, which means you can use jQuery methods to traverse through the DOM:
elements.eq(1).find("div").append(item);
Demo: http://jsfiddle.net/rgQ7g/
.eq(1) selects the second item but returns it wrapped in another jQuery object, so then you can use .find("div") to get to the child div and .append() your item to it.
Try after():
$('.play').find('p').after(item);
This inserts content AFTER a selected element in the DOM. It also does it for all the classes named .play
If you need to specify an index, I recommend a function:
function appendPlay(index, content) {
$('.play').eq(index).find('p').after(content);
}
appendPlay(2, '<p>HTML to be inserted</p>');
jsFiddle
please try using
var element = $('.play div p');
var item = '<p>HTML to be inserted</p>'
$(element).parent().append(item);
Edited
from
var element = $('.play div');
var item = '<p>HTML to be inserted</p>'
$(element).append(item);
Well, I guess this would work:
$(item).appendTo($(elements));
But a better solution would be using:
$('.play').find('p').after(item);
You can use link below. (I edited code after comment)
You should write code like;
var selector = ".play",
text = "<p>HTML to be inserted</p>";
$(selector + " div p").eq(1).after(text);
http://jsbin.com/esesul/5/

Clone a div and make ID's of it it's children to be unique using javascript

I need to clone a div and after cloning all the elements within the div should have unique ids. I need to do this using javascript only and not jquery.
Can anyone help me please.
The following code clones an element, uses a recursive function to assign random id's to the cloned element and its children and appends it to the document body. Adjust to your needs. See also this jsfiddle
var someClone = someDiv.clone(true), children = someClone.childNodes;
someClone.id = Math.floor(1000+Math.random()*10000).toString(16);
reId(children);
function reId(nodes){
for (var i=0;i<nodes.length;(i+=1)){
var children = nodes[i].childNodes;
nodes[i].id = Math.floor( 1001+Math.random()*10000 ).toString(16);
if (children.length){
reId(children);
}
}
}
document.body.appendChild(someClone);

How to use jQuery selector/find() against text string without inserting into the DOM?

I have a text string i'm trying to select the spans from using jQuery. I'd like to grab the spans w/o adding the element to the dom -- if that's possible?
After reading the jquery docs i was under the assumption that i could create a fragment by wrapping the string in a jquery selector tag, then using.find() to find the elements i want.
I have code that is similar to this but from the looks of the last line, it's obvious that no spans are being selected; any help would be greatly appreciated:
// 'text' is normally generated automatically...
// just made it an escaped string for example purposes.
var text ="<span id=\"blah1\">Y</span><br/><span id=\"blah2\">o</span><br/>";
var spans = $(text).find('span');
console.log(text); // => <span id="blah1">Y</span><br/><span id="blah2">o</span><br/>
console.log(spans.length); // => 0
Thanks.
You want to use filter(), not find()
var text ="<span id=\"blah1\">Y</span><br/><span id=\"blah2\">o</span><br/>";
var spans = $(text).filter('span');
console.log(spans.length);
jsFiddle
From the jQuery docs
filter:
The supplied selector is tested against each element; all elements
matching the selector will be included in the result.
find:
the .find() method allows us to search through the descendants of
these elements in the DOM tree and construct a new jQuery object from
the matching elements.
with your html fragment, there is no wrapper element, so there is no descendants, hence why find() does not work.
You are basically doing:
var elems = jQuery("<span id=\"blah1\">Y</span>").add("<br/>").add("<span id=\"blah2\">o</span>").add("<br/>");
If you want find to work with find(), you need to wrap it in an element.
var text ="<span id=\"blah1\">Y</span><br/><span id=\"blah2\">o</span><br/>";
var spans = jQuery("<div></div>").append(text).find("span");
console.log(spans.length);
You want to use filter in this case:
var text ="<span id=\"blah1\">Y</span><br/><span id=\"blah2\">o</span><br/>";
var spans = $(text).filter('span');
console.log(spans.length); // 2
Demo: http://jsfiddle.net/ambiguous/TGY3J/
Or wrap it in a <div> and use find:
var text ="<span id=\"blah1\">Y</span><br/><span id=\"blah2\">o</span><br/>";
var spans = $('<div>' + text + '</div>').find('span');
console.log(spans.length); // 2
Demo: http://jsfiddle.net/ambiguous/qbCjk/
find works on descendants but without the <div> wrapper, your $(text) doesn't have any <span> descendants. Wrapping your HTML in a <div> is probably your best bet, that way you don't have to worry about how deep your desired elements are.

Categories