JavaScript/Jquery nodes from ID - javascript

Hello I want to get the nodes of class "ms-qSuggest-listItem" from the id.
<div class="ms-qSuggest-list" id="ctl00_ctl38_g_c60051d3_9564_459e_8a40_e91f8abf4dcf_csr_NavDropdownList" style="width: 508px;">
<div class="ms-qSuggest-listItem">Everything</div>
<div class="ms-qSuggest-listItem">Videos</div>
<div class="ms-qSuggest-hListItem">People</div>
<div class="ms-qSuggest-listItem">Conversations</div>
</div>
I tried
var nodes = $get("ctl00_ctl38_g_c60051d3_9564_459e_8a40_e91f8abf4dcf_csr_NavDropdownList").class(ms-qSuggest-listItem);
If I wanna get the nodes from its direct class - here its working but I want to get it from the ID.
var nodes = $("div.ms-qSuggest-listItem");
Please help.
Thanks.

All the below selectors will give you the matching nodes.
var nodes = $("#ctl00_ctl38_g_c60051d3_9564_459e_8a40_e91f8abf4dcf_csr_NavDropdownList").find('.ms-qSuggest-listItem');
OR
var nodes = $("#ctl00_ctl38_g_c60051d3_9564_459e_8a40_e91f8abf4dcf_csr_NavDropdownList .ms-qSuggest-listItem");
OR
var nodes = $(".ms-qSuggest-listItem", "#ctl00_ctl38_g_c60051d3_9564_459e_8a40_e91f8abf4dcf_csr_NavDropdownList");
Demo: https://jsfiddle.net/tusharj/fr2d9yv1/

You can use the id in conjunction with the class name within the same selector like this:
var long_id = 'ctl00_ctl38_g....';
var nodes = $('#' + long_id + ' .ms-qSuggest-listItem');
Basically what is happening here is the selector is matching the id and then looking inside it's children for the specified class name.
A more explicit way of writing this would be to use the .find() function on the parent node itself.
Description: Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
var long_id = 'ctl00_ctl38_g....';
var parent_node = $('#' + long_id);
var children_nodes = parent_node.find('.ms-qSuggest-listItem');
JSFiddle demo

Related

JavaScript- how to print p element inside div

I Know I can do this with static HTML, but I want to create dynamically, and I am struggling a lot.
Here is what I want to do:
I have 2 divs.
<div class="TxtTile">
</div>
<div class="pInfo">
</div>
Inside each div I want to have several paragraphs. Let's say 10, in each div.
The first div with class "TxtTile" i want to have the title of something, let's say titles like, age,country,experience,street etc.In the other div with class 'pInfo' I want to contain the information that corresponds with TxTtitle.
Like, age 25, experience 10 years etc, that will be taken from local Storage, where I already have it set up. This two divs will be next to each other, which I have already done with css.
For example.
Left side
<div class="TxtTile"> `<div class="pInfo">
<p class="styleforP"> <p class="styleforP">
Age 25
</p>
</p>
</div> </div>`
I would be happy if I can make this with native js.
There are two ways you can do this:
1) you can create an element and keep appending to its place
First get div element inside which you want to create new element, Here rather than having a class i would prefer to have id based selection of the element
var element = document.querySelector('.TxtTile');
Create a p element and add class to it, you can similarly add content inside it aswell
var pElem = document.createElement('p');
pElem.className = 'styleforP';
pElem.innerHTML = 'Age';
Append that created element inside your div
element.appendChild(pElem);
2) Create an HTML template pass your values to that template and create innerHTML and directly put that innerHTML into your parent element
var item = {
name: "My Name",
age: 30,
other: "Other Info"
}
var template = [];
template.push(
'<div class="row">',
'<span class="name-info">' + item.name + '</span>',
'<span class="age-info">' + item.age + '</span>',
'<span class="other-info">' + item.other + '</span>',
'</div>'
);
var htmlString = template.join('');
var element = document.querySelector('.TxtTile');
element.innerHTML = htmlString;
If you are going to add a lot of items then second approach is a lot better, as creating single element and appending them to DOM tree is quite slow, then passing whole HTML string.
var myData = {
title: "My title",
info: 25
};
// Store references to the wrapper elements
// The first element that has this class, or null if there aren't any
var titleWrapper = document.querySelector(".js-titleWrapper");
var infoWrapper = document.querySelector(".js-infoWrapper");
// Create the paragraph elements
var titleP = document.createElement("p");
var infoP = document.createElement("p");
// Add classes
titleP.classList.add("styleForP");
infoP.classList.add("styleForP");
// Add the text
titleP.innerText = myData.title;
infoP.innerText = myData.info;
// Add the paragraphs to their wrappers
titleWrapper.appendChild(titleP);
infoWrapper.appendChild(infoP);
<div class="TxtTile js-titleWrapper">
</div>
<div class="pInfo js-infoWrapper">
</div>
i think this is a bad idea for doing this if you have multiple records then you cant handle by querySlector.
good idea is create a parent element like this
<div id="parent"></div>
then get this element by javascript and then append this element with your dynamic records like this
var parentEle = document.getElementById("parent");
apply loop if records are multiple
var child = Document.createElement("div");
child.innerHTML = "<div class='TxtTile'>age</div><div class='pInfo'>25</div>";
parentEle.appendChild(child);

Get elements 'tag name' by searching Class name

I'm trying to get element tag name which is associated with the element with a certain class name.
I know I can do these two lines of code to get the class name and the tag name.
document.getElementsByTagName("regeneratePostnatal");
document.getElementsByClassName(returnedPatientID);
I'm just asking if there is a way of doing something like below to get the tag name which belongs to the element with the class name?
document.getElementsByClassName(returnedPatientID).tagName
Example
var element = document.getElementsByClassName("oneID")[0].tagName;
document.getElementById("returnedValue").innerHTML = element;
var element2 = document.getElementsByClassName("oneID")[0].nodeName;
document.getElementById("returned2Value").innerHTML = element2;
<a class="oneID" name='regeneratePostnatal'>Click</a>
<div id="returnedValue"></div>
<div id="returned2Value"></div>
I'm trying to get the name attribute value so that it'll show "regeneratePostnatal"
Are you trying to get the attribute name value?
var element = document.getElementsByClassName("oneID")[0].getAttribute('name');
document.getElementById("returnedValue").innerHTML = element;
<a class="oneID" name='regeneratePostnatal'>Click</a>
<div id="returnedValue"></div>
The property you are looking for is nodeName:
document.getElementsByClassName(returnedPatientID)[0].nodeName
W3Schools
Yes you can get the tagName but you need to use index as getElementsByClassName returns a collection of array. So to get the tagName:
console.log(document.getElementsByClassName('YourClass')[0].tagName);
//Or in a loop
var len = document.getElementsByClassName('YourClass').length;
for(var i=0;i<len;i++){
console.log(document.getElementsByClassName('YourClass')[i].tagName);
}

Javascript get class text inside element

I have a bunch of span4 class elements in my html. they look something like this:
<div class="span4">
<div class="widget">
<div class="header">blablabla</div>
</div>
</div>
I want to sort the span4 by that text iside header class.
I do this to sort them
$(".span4").sort(sortAlpha)
but how do I select the text inside the header class?
I'm doing this but I guess there is a better way
function sortAlphaAsc(a,b){
var nomeA = $(a.childNodes[1].childNodes[1]).text();
var nomeB = $(b.childNodes[1].childNodes[1]).text();
return a.innerHTML.toLowerCase() > b.innerHTML.toLowerCase() ? 1 : -1;
};
there must be a better way than
$(a.childNodes[1].childNodes[1]).text()
var elems = $(".span4");
elems.sort(function(a, b) {
return $(a).find('.header').text().toUpperCase().localeCompare(
$(b).find('.header').text().toUpperCase()
);
});
$(".span4").parent().html(elems);​
FIDDLE
Try this:
function sortAlphaAsc(a,b){
var nomeA = $(a).find('div.header').text();
var nomeB = $(b).find('div.header').text();
return nomeA.toLowerCase() > nomeB.toLowerCase();
};
You could detach the spans, sort and append them.
That will be very fast too as changing elements in memory and only updating the DOM once in the end is very efficient.
var $spans = $(".span4").detach();
var sortedSpans = $spans.sort(function(spanA, spanB) {
var spanTextA = $("div.header", spanA).text();
var spanTextB = $("div.header", spanB).text();
return spanTextA > spanTextB;
});
$("body").append(sortedSpans);
Obviously instead of body you append it back to it's actual container element.
Or if the spans are in a common container store the parent in cache var $parent = $spans.parent() and in the end simply do $parent.html(sortedSpans).
I don't know your whole mark-up but that should get you started.
DEMO - Detach spans, sort them and append again
Do you mean something like this:
$('.span4').find('.header').text();
This will return the text inside the header div.

How to search the children of a HTMLDivElement?

I have an HTMLDivElement, and my goal is to find a div nested beneath this.
Ideally I'd want something like getElementById, but that function doesn't work for HTMLDivElement.
Do I need to manually traverse the graph, or is there an easier way?
Demo: http://jsfiddle.net/ThinkingStiff/y9K9Y/
If the <div> you're searching for has a class, you can use getElementsByClassName():
document.getElementById( 'parentDiv' ).getElementsByClassName( 'childDiv' )[0];
If it doesn't have a class you can use getElementsByTagName():
document.getElementById( 'parentDiv' ).getElementsByTagName( 'div' )[0];
And if it has an id you can, of course, just use getElementById() to find it no matter where it is in the DOM:
document.getElementById( 'childDiv' );
//For immediate children
var children = document.getElementById('id').childNodes;
//or for all descendants
var children = document.getElementById('id').getElementsByTagName('*');
var div = ...
var divChildren = div.getElementsByTagName("div");
var divYouWant = [].filter.call(divChildren, function (el) {
return matchesSomeCondition(el);
});
Ideally, I'd want something like getElementById
And you can use getElementById just do document.getElementById(id) and since ids are unique that will find that single div item you wanted.
You can also use elem.getElementsByClassName to select a descendant of elem by class
You can use .querySelector(). The functions getElementById() and getElementByClassName() work perfectly fine on document, but they do not work on the child records returned by these functions. If you need many children elements, then consider .querySelectorAll()
Full Working Demo:
const topdiv = document.getElementById('top-div');
const seconddiv = topdiv.querySelector('#second-div');
seconddiv.innerHTML = '456';
<div id="top-div">
123
<div id="second-div">
abc
</div>
</div>
Demonstration of getElementById() Failing:
const topdiv = document.getElementById('top-div');
const seconddiv = topdiv.getElementById('second-div');
seconddiv.innerHTML = '456';
<div id="top-div">
123
<div id="second-div">
abc
</div>
</div>
Concise and readable:
document.getElementById('parentDiv').children[0];
Using .childNodes returns lots of extra children, whereas .children returns a smaller array.

Check for duplicates when creating children for div

I would like to check that I am not creating a child with a duplicate title. However, I am not sure of the correct way to check and compare. Here's a code example of how the div's children are added:
this.foo = function(inputTitle)
{
var title = inputTitle;
var $ItemContainer = $("#ItemContainer");
$ItemContainer.append('<div class="Item" title="'+title+'"></div>');
// Continue to build the child
var $thisItem = $ItemContainer.children('.Item[title='+title+']');
$thisItem.append('<div class="ItemTitle">'+title+'</div>');
// .....
}
The class will always be Item. How can I check that #ItemContainer does not already have a child with a duplicate title?
The following will tell you if there are any divs with a given title
var exists = $('div[title="' + title + '"]').length > 0;

Categories