Jquery: find element in var and change text - javascript

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);

Related

How to get node inside a node

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

java script replace for html attributes

I have a html tag like the following:
<div id="slide1" class="mySlides" type="slide" index="1" duration="1100" style="display: block;">
<div id="page_number1" class="numbertext">1/2</div>
<div id="slide_content1"><p>First Slide</p>
</div>
<div id="slide_h1" class="slide_h1"></div>
<div id="slide_h2" class="slide_h2"></div>
<div id="playOptions{slide_number}" class="playOptions">|
<span id="remaining_slide_time{slide_number}"></span> |
<span id="remaining_time{slide_number}"></span>
</div>
</div>
</div>
I need to replace {slide_number} with an integer. Whatever I tried the result doesn't replace the {slide_number}
var str = template.replace("{slide_number}", i);
You can use attribute selector contains that will select all elements where id contains {slide_number} and you can replace that part of the id with the number.
document.querySelectorAll("[id*='{slide_number}']").forEach(function(e) {
e.id = e.id.replace("{slide_number}", 1)
})
<div id="slide1" class="mySlides" type="slide" index="1" duration="1100" style="display: block;">
<div id="page_number1" class="numbertext">1/2</div>
<div id="slide_content1">
<p>First Slide</p>
</div>
<div id="slide_h1" class="slide_h1"></div>
<div id="slide_h2" class="slide_h2"></div>
<div id="playOptions{slide_number}" class="playOptions">|
<span id="remaining_slide_time{slide_number}"></span> |
<span id="remaining_time{slide_number}"></span>
</div>
</div>
in javascript you can find them from
document.querySelector('[id$="{slide_number}"]').id;
and
document.querySelector('[id*="{slide_number}"]').id;
Please read this
If you use jquery then it can be done like below:
$('#playOptions').attr('id','playOptions88');
But I recommend you to use HTML data attribute to distinguish different element. It is a very nice thing to work with multiple elements that can be needed to change dynamically.
If you change your ID attribute dynamically adding some integer number then it may be harder to catch them. Instead, use data like below code.
You can make any element unique setting the data-SOMETHING.
If you write the code below:
$('#playOptions').data('roll','100');
Then the element will be
<div id="playOptions" data-roll="100" class="playOptions">
If you write the code below:
$('#playOptions').data('name','ahmad');
Then the element will be
<div id="playOptions" data-name="ahmad" class="playOptions">
You can then catch the element by the code below:
var name = $('#playOptions').data('name');
console.log(name) //Output should be 'ahmad'
Similarly,
var roll = $('#playOptions').data('roll');
console.log(roll) //Output should be '100'
To learn more about the data attribute please see the link
https://api.jquery.com/data/
This solution worked:
var find = '{slide_number}';
var re = new RegExp(find, 'g');
str = template.replace(re, i);

jQuery - get part of DOM as string

I have a html code like this:
<div id="sample" style="height: 100px">
<div class="test">
...
</div>
<div class="test">
...
</div>
<div class="test">
...
</div>
...
</div>
I need to get <div id="sample" style="height: 100px"> string from this DOM. How can I do this?
Assuming you want to get the div's HTML as a string without the children in that string, an approach could be to select the element, clone it (to avoid messing with the DOM), wrap the clone in another element, crawl up to that element and take that elements contents.
var str = $("#sample").clone().empty().wrap("<div/>").parent().html();
Here's a jsfiddle-demo. So to clarify:
.clone() yields:
<div id="sample" style="height: 100px">
<div class="test">
...
</div>
<div class="test">
...
</div>
<div class="test">
...
</div>
...
</div>
.empty()
<div id="sample" style="height: 100px"></div>
Side note: From here, instead of using .wrap().parent().html(), you could fetch the original DOM-element and access the outerHTML-attribute (i.e. $("#sample").clone().empty()[0].outerHTML). However, the first-mentioned approach defies cross-browser compatibility issues.
.wrap("<div/>")
<div><div id="sample" style="height: 100px"></div></div>
.parent() refers to the newly created outer div, and .html() returns the content of that, which will leave you with the string <div id="sample" style="height: 100px"></div>
Try this
var str = $('#sample')[0].outerHTML.split('\n')[0];
alert(str);
http://jsfiddle.net/d27frp8a/
Just another way:
var element = $('#sample')[0];
var outer = element.outerHTML;
var inner = element.innerHTML;
var line = outer.substring(0, outer.indexOf(element.innerHTML));
Get the string representation of full element
Get the string representation of the content inside
Get a substring from the beginning to a shift of inner part

Getting class contains in a very simple Jquery plugin

I'm experimenting with Jquery plugins. (please note I'm a beginner) and I've made a very simple plugin. this works if I set the selector to ('div') but when I try to make it so it only selects the divs with a class that contains "object" it fails. what am I doing wrong? I'm not getting any errors.
javascript:
(function( $ ) {
$.fn.Duplo = function() {
return this.filter("div[class*='object']").clone().appendTo('body');
};
}( jQuery ));
$(document).ready(function(){
$( ".negen" ).Duplo();
});
html:
<body>
<div class="row">
<div class="col-md-12 col-sm-12 twaalf">
</div>
</div>
<div class="container">
<div class="col-md-3 col-sm-3 drie">
</div>
<div class="col-md-9 col-sm-9 negen">
<div class="object"></div>
<div class="object2"></div>
<div class="object3"></div>
<div class="object4"></div>
</div>
</div>
</body>
My html contains four divs with the classes: object, object1, object2, object3 Also .negen is the div wich contains all of these.
Thanks :)
If you expect to filter .negen elements which contains some specific elements with class containing object, then use:
this.filter(":has(div[class*='object'])").clone().appendTo('body');
This could be written as:
return this.has("div[class*='object']").clone().appendTo('body');
If you want to clone elements object, then use:
return this.find("div[class*='object']").clone().appendTo('body');
You have to change your selector statement
"("div[class*='object']")" this part
check this
http://api.jquery.com/category/selectors/
Try this.
return this.find(".object").clone().appendTo('body');
Fiddle Demo

How should I edit strings across many instances of the same html?

I've got this code below, with different data, repeated over 10 times on the page I am working on:
HTML:
<div class="kpaGraph">
<p>Target: 43%</p>
<div class="progress">
<div class="bar"></div>
</div>
</div>
<div class="kpaBottom">
<div class="strong">
<p>311</p>
</div>
<div class="weak">
<p>number of teachers trained</p>
</div>
</div>
I want to alter the number in div.strong p (311) based on the number in div.kpaGraph p (43%) in the same manner across all instances of this code with Javascript/ jQuery. What is the cleanest way to do this? Should I select all $('div.kpaGraph p') and then use each() Or should I create a function and run it on all of them?
Thanks!
You can use the following to find the proper element in conjuntion with an .each() on $('div.kpaGraph p'):
$(this).parent().next('div.kpaBottom').find('div.strong p')
For example, using the following will take the value in the kpaGraph p node and append it to the p node in the following kpaBottom node:
$('div.kpaGraph p').each(function () {
$(this).parent().next('div.kpaBottom').find('div.strong p').html('foo');
});
jsFiddle example
There are a few ways.
You can use "next".
$('.kpaGraph').each(function(){
var $kpaStrong = $(this).next('.kpaBottom .strong p');//this is the elm that has 311
});
Or you have to somehow create a relation between them so you know they go together, like a common parent.
<div class="kpaWr">
<div class="kpaGraph">
<p>Target: 43%</p>
<div class="progress">
<div class="bar"></div>
</div>
</div>
<div class="kpaBottom">
<div class="strong">
<p>311</p>
</div>
<div class="weak">
<p>number of teachers trained</p>
</div>
</div>
</div>
Then with jQuery you can select it like so:
$('.kpaGraph').each(function(){
var $kpaStrong = $(this).closest('.kpaWr').find('.kpaBottom .strong p');//this is the elm that has 311
});
Something like this might be pretty clean too:
$("div.strong p").text(function(index, text){
return $(this).closest("div.kpaBottom").prev("div.kpaGraph").find("p").text();
});
That would change the text to Target: 43% in your example.

Categories

Resources