How to get node inside a node - javascript

Let's suppose I have a variable called myNode:
myNode = document.getElementsByTagName('li')[0];
Here is what myNode.outerHTML looks like:
<li>
<div class="_4ofi">
<div class="_4ofp">
<div class="_4ofr">
<div class="_2hq-">
<i class="img sp_RGPCxTkOR8i_1_5x sx_20baa4" alt=""></i>
</div>
</div>
<div class="_4ofr">
<div>My div</div>
<div class="_9079">My caption</div>
</div>
</div>
<div class="_4ofr">
<div aria-checked="false" aria-disabled="false"
class="_kx6 _kxa _4ofs" role="checkbox" tabindex="0">
</div>
</div>
</div>
</li>
I need to access the div that starts with <div aria-checked="false"> but as this div has no ID. I suppose I need to iterate through the myNode elements to find it and click on it.
So I tried this:
for (var i=0;i<myNode.length;i++) { console.log(myNode[i]); };
Somehow myNode.length returns undefined.
What am I missing?

If you use document.querySelector, you can select an element by an attribute.
document.querySelector('li div[aria-disabled="false"]')
If the classes are not going to change, you can increase the specificity of the selector. If myNode is a list of li (list items), then you can query from that node at the desired index.
myNode[i].querySelector('._4ofi ._4ofr div[aria-disabled="false"]')
Additionally, you could iterate over the result set to increase readability.
myNodes.forEach(node => myNode.querySelector('div[aria-disabled="false"]'));
Where myNodes is a collection of li elements.

I assume you cannot modify the DOM. Otherwise just set an id to the element you want to access and get it by using
document.getElementById('myId')
If you cannot touch the DOM:
myNode.length returns undefined because the returning value is not an array. It is an object. You access its child nodes by calling
myNode.childNodes
For the specific node that has the "aria-check". You can access directly with:
document.getElementsByTagName('li')[0].childNodes[1].childNodes[3].childNodes[1]
Not sure why someone would like to access a node in that way, but there you go.

var myNode = document.getElementsByTagName('li');
for (var i=0;i<myNode.length;i++) {
console.log(myNode[i].querySelector('._4ofr div[aria-disabled="false"]'));
};
try this it will give you aria-checked="false" div content, fiddle link

Related

How to get value inside a div element using JS

Here I have a div element with class med and I want to access the value inside the div of the Prescribed:{{pro_id.prescribedmed}} .I tried JS to get the value by using the getattribute() but it does not show. how can get the value of it. Here is the piece of code
<div class="column">
<!-- style="background-color:#bbb; -->
<p class="newarrival ">Rs.{{pro_id.price}}</p>
<h4>{{pro_id.name}}</h4>
<p><strong>Category:</strong> {{ pro_id.category}}</p>
<p><strong>Description:</strong> {{pro_id.smalldescription}}.</p>
<div class="med hidden" >
<p>Prescribed:{{pro_id.prescribedmed}}</p>
</div>
<button data-product={{pro_id.id}} data-action="add" type="button" class="btn-cart update-cart"> Add to cart
</button>
</div>
i tired to get the element like
var premed = document.getElementsByClassName('med').innerText;
console.log(premed)
here the output gives like undefined
Give this a try
<p class="med_prescribed">Prescribed: {{ pro_id.prescribedmed }}</p>
in your JS as follows
var premed = document.getElementsByClassName('med_prescribed')[0].innerText;
console.log(premed);
If I had to do that it would look next:
First select the element with Document.querySelector().
Then extract the text of the element.
And finally use the String.prototype.substring() method to get the needed value.
You cant get the attribute because you dont have one.
Div element:
<div class="med hidden" id="Div_id" value="Value_here" >
JS:
var value = document.getElementById("Div_id").getAttribute ("value")

Jquery: find element in var and change text

the following expression is not working: (neither with .text())
$(file.previewElement).find('[data-dz-name]').html(file.name);
File.previewElement is a variable = $(".preview-template").html();
For $(file.previewElement).find('[data-dz-name]')the debugger outputs:
Object { 0: <span>, length: 1, prevObject: Object, context: undefined, selector: "[data-dz-name]" }
This is about following Code:
<div class="preview-template" style="display: none;">
<div class="body content ig">
<div class="dz-preview dz-file-preview">
<h2 class="dz-filename">File: <span data-dz-name></span></h2>
<img class="dz-thumb" data-dz-thumbnail />
<div class="dz-progress"></div>
<div class="dz-error-message"><span data-dz-errormessage></span></div>
Details:
<div class="dz-size" data-dz-size></div>
<div class="dz-success-mark"><span>✔</span></div>
<div class="dz-error-mark"><span>✘</span></div>
</div>
</div>
</div>
You are using the entire HTML content as a selector, which is not valid do to. If you want your variable to be a selector change your variable to be $(".preview-template"), removing the .html() on the end.
For having file.previewElement as a separate instance variable for your HTML element you can use (as you already found out) $.parseHTML(). Which will give you a array of nodes that you can manipulate using jQuery:
file.previewElement = $.parseHTML($(".preview-template").html());
Use $(".preview-template").find('[data-dz-name]').html(file.name);
Update your code from
$(file.previewElement).find('[data-dz-name]').html(file.name);
to
$(".preview-template").find('[data-dz-name]').html(file.name);
In case you need to have variable for the element and also for the template then you have to introduce a new variable and update your code like following
file.previewElement = $(".preview-template");
file.previewTemplate = file.previewElement.html();
file.previewElement.find('[data-dz-name]').html(file.name);

Dragula drop in multiple divs

I implemented drag 'n' drop on my application using Dragula, but I need to set it so I can drop my elements to more than one div.
I tried to use a class to achieve it, but it just activates the first one of my divs.
THe HTML:
<div role="presentation" class="table table-striped">
<div class="files" id="upload-file"></div>
</div>
<div class="col-md-4">
<div class="drag-container">Test 1</div>
<div class="drag-container">Test 2</div>
<div class="drag-container">Test 3</div>
</div>
The JS calling Dragula:
dragula([document.querySelector('#upload-file'), document.querySelector('.drag-container')]);
How can I drop te items to more than one div?
You can define an array containers:
var containers = $('.drag-container').toArray();
containers.concat($('#upload-file').toArray());
And then, pass the var 'containers' to dragula initializer:
dragula(containers, {
isContainer: function (el) {
return el.classList.contains('drag-container');
}
});
For those without jQuery or $ you can use:
dragula([].slice.call(document.querySelectorAll("drag-container")));
This converts the NodeList to an array and passes it to dragula.
querySelector only returns a single element, you would need to use querySelectorAll in order to get a list of elements. Not sure how dragula would handle getting a two element array, with the second element being an array. You may want to generate the array first, add the '#upload-file' to that array, and then pass the array. Or you could generate the array after initializing, and cycle through the array, adding the elements dynamically using something like "drake.containers.push(container);". I got this construct directly from the github site https://github.com/bevacqua/dragula
HTML:
<div className="wrapper">
<div className="container col-md-4" id="A">
<div className="panel panel-white">
</div>
<div className="panel panel-white">
</div>
</div>
<div className="container col-md-4" id="B">
<div className="panel panel-white">
</div>
<div className="panel panel-white">
</div>
</div>
</div>
JS:
dragula([document.querySelector('#A'), document.querySelector('#B')]);
You can drag each item in one column to the other. You can add more columns with the class name of container.
If you want to specify a custom class name, you should define option like this :
Option:
let options = {
isContainer: (el) => {
return el.classList.contains('drag-container'); // The immediate elements in this container will be draggable
}

JQuery: How to get all bottom-most children in a DOM tree?

Based on the DOM tree below, I want to get all of the <p> element that are the child of every div with message as its class and put them all in an array. This will create an array of objects.
Note : ul and all of its children in all levels can be added dynamically to the dom at any given time.
How do I do that?
I have tried
var messages = $('.rightP').find('li>.message>p');
$.each(messages,function(){
console.log(this);
});
but no luck
DOM tree
<ul class="rightP">
<li>
<div class="sender">
<p>David</p>
</div>
<div class="message">
<p>Hello</p>
</div>
</li>
<li>
<div class="sender">
<p>Watson</p>
</div>
<div class="message">
<p>yes anything?</p>
</div>
<div class="message">
....
</li>
...
</ul>
You used wrong jQuery selector. Replace $('.rightP').('li>.message>p') with $('.message > p') or you could do it this way.
var messages = jQuery('.message > p');
jQuery.each(messages, function (index, elem) {
var message = jQuery(elem);
console.log(message.text())
});
Here's the working fiddle.
$('.rightP').('li>.message>p');
Wrong statement. You should try
$('.rightP').find('li>.message>p');
etc...
You can get all those like bellow
var messages = $('.rightP').find('li>.message>p');
$.each(messages,function(){
console.log(this);
});

selecting span value inside div

Let's say I have
<div id="1">
<span id="name">Josh</span>
<div id="quote">Run</div>
</div>
<div id="2">
<span id="name">Mark</span>
<div id="quote">Run</div>
</div>
How would I select the name between the span tags from the first div?
$("#quote").click(function(){
var name = $('#name').html();
});
Firstly, id's have to be unique in an html document. So,ideally, you need to change those id's within the div to a class. Secondly, id's cannot begin with a numeric, so you need to change your div id's to start with a letter or underscore.
With that in mind, given this structure:
<div id="one">
<span class="name">Josh</span>
<div class="quote">Run</div>
</div>
<div id="two">
<span class="name">Mark</span>
<div class="quote">Run</div>
</div>
you would be looking for:
$("#quote").click(function(){
var name = $('#one .name').html();
});
id's should be unique across a page. You should change the name and quote id's to a class, which do not have to be unique.
<div id="1">
<span class="name">Josh</span>
<div class="quote">Run</div>
</div>
<div id="2">
<span class="name">Mark</span>
<div class="quote">Run</div>
</div>
You could then select via:
$('#1 .name')
You should also bare in mind that id's should not start with a number (except in HTML5)
var name = $("#1 span").html()
or
var name = $('#1 #name').html();
this should work for you:
$("#1 span").text();
You have some problems with your HTML though. You should not have any duplicate IDs in your HTML, they must be unique. ID shouldn't start with a number either.
You can view the fiddle here: http://jsfiddle.net/
you can select the first span tag content of your div #1 this way as well :
var name = $("#1 span:first").html();
Adding #1 before #name would select the first div
$("#quote").click(function(){
var name = $('#1 #name').html();
});

Categories

Resources