java script replace for html attributes - javascript

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

Related

How to target child div by Javascript?

I want to apply JavaScript on sticky header in my site. For this I want to target a div inside sticky div by JavaScript. Please let me know how to target a dive that is inside some other divs by JavaScript.
var yourHTML = '<div class="mynewdiv">Test</div>';
document.getElementsByClassName('at-sticky' 'custom-logo-link')
[0].innerHTML = yourHTML;
<div class="at-sticky">
<div class="container">
<div class="navbar-header">
<a href="#" class="custom-logo-link"
rel="home" itemprop="url">
<img src="#" class="custom-logo">
</a>
</div>
</div>
</div>
You can try with Document​.query​Selector() which allows CSS like selector:
var yourHTML = '<div class="mynewdiv">Test</div>';
document.querySelector('.at-sticky .custom-logo-link').innerHTML = yourHTML;
<div class="at-sticky">
<div class="container">
<div class="navbar-header">
<a href="#" class="custom-logo-link"
rel="home" itemprop="url">
<img src="#" class="custom-logo">
</a>
</div>
</div>
</div>
Please use querySelector()
var yourHTML = '<div class="mynewdiv">Test</div>';
document.querySelector('.at-sticky .custom-logo-link').innerHTML = yourHTML;
Simplest solution is using querySelector
Example:
document.querySelector('.at-sticky .container .custom-logo-link').innerHTML = yourHTML
Please put the comma in between the class names:
document.getElementsByClassName('at-sticky', 'custom-logo-link')[0].innerHTML = yourHTML;
Ok 2 points:
Firstly when using innerHTML you are inserting text into your element, not the full tag as you have done.
Secondly you only need pass in to ‘document.getElementsByClassnames’ the class name that you are targeting. Dont worry about the parent div, that should work fine as is.
I would have posted a comment but I don’t have enough reputation yet;)
You can use children() function for this.
$('.at-sticky').children();
You can use querySelector for this.
Let's say you have the following HTML structure
<div class="parentDiv">
</div>
Then you can do this in JavaScript
let parentDiv = document.querySelector('.parentDiv')
let childLink = parentDiv.querySelector('a')
console.log(childLink)

How can i retrieve informations from html tags in Javascript?

I am trying to pull certain item IDs based on if they have an image tag or not. For a given input like the one below:
<div id="ID_1">
<p><img src="image4.png"></p>
</div>
<div id="ID_2">
</div>
<div id="ID_3">
<p><img src="image6.png"></p>
</div>
<div id="ID_4">
<p><img src="image4.png"></p>
</div>
I could get something like:
ID_1: image4.png
ID_2:
ID_3: image6.png
ID_4: image4.png
I am not too familiar with HTML or Javascript, so any help or resources that someone may have or know will be greatly appreciated.
I would recommend using jQuery for something like this
(dont forget to include jquery in the html head)
Html =>
<div id="divContainer" >
<div id="ID_1">
<p><img src="image4.png"></p>
</div>
<div id="ID_2">
</div>
<div id="ID_3">
<p><img src="image6.png"></p>
</div>
<div id="ID_4">
<p><img src="image4.png"></p>
</div>
</div>
Javascript =>
const doesContainImg = [];
$(".divContainer div").each(function() {
// check for an img
if ($(this).find("img").length) {
// store id in array that contains ids that have imgs
doesContainImg.push($(this).attr("id"));
}
});
that should work, if it does not let me know!
Add a class on those div.
Let's say you have the class "image-div".
We can use this class to see if the divs contain an image or not.
JQUERY:
$(".image-div").each(function(){
if($(this).find('img').length){
//if this div contains an image do something.
}
});
You can attach this code to an event and use it

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

How to replace strings in jQuery DOM element

I need to build HTML from an jQuery ajax response. I don't like nesting ugly strings in javascript and I don't want to use mustache or any other templating script.
So I went for the approach of having a template HTML with display: none like the following:
<div id="message-template" class="message-tile" style="display: none;">
<div class="profile-thumb"><img src="{{thumb-url}}" width="48" height="48" alt="{{person-name}}" /></div>
<div class="message-data">
<div class="message-info">
<div class="sender-name">
{{person-name}}
</div>
<div class="posted-to">
To {{posted-to-title}}
</div>
</div>
<div>{{message-body}}</div>
</div>
</div>
I want to be able to replace the strings between {{ }} with the actual values from the json object.
Suppose this is the function that gets called on the jQuery.ajax onSuccess event:
function createNewElement(jsonObj) {
var $clone = $('#message-template').clone();
$clone.replaceString("{{person-name}}", jsonObj.personName);
$clone.replaceString("{{thumb-url}}", jsonObj.thumbUrl);
$clone.replaceString("{{person-url}}", jsonObj.personUrl);
// etc
$("#target-container").append($clone);
}
I invented the replaceString method, but is there something similar? Or do I need to traverse through each element child using find() ?
Actually you can use <script type = "text/template"> to create your own templates, this way it won't render on your page:
<script id="message-template" type = "text/template">
<div class="message-tile" style="display: none;">
<div class="profile-thumb"><img src="{{thumb-url}}" width="48" height="48" alt="{{person-name}}" /></div>
<div class="message-data">
<div class="message-info">
<div class="sender-name">
{{person-name}}
</div>
<div class="posted-to">
To {{posted-to-title}}
</div>
</div>
<div>{{message-body}}</div>
</div>
</div>
</script>
Here's how you substitute your values:
function createNewElement(jsonObj) {
var $clone = $('#message-template').html();
$clone = $clone.replace("{{person-name}}", jsonObj.personName)
.replace("{{thumb-url}}", jsonObj.thumbUrl)
.replace("{{person-url}}", jsonObj.personUrl);
// etc
$("#target-container").append($clone);
}
There is a replace() method that can accept a regex, which would make it much more flexible.
Something like this would do it...
html.replace(/\{\{([^}]+)\}\}/g, function(all, key) {
return jsonObj[key] || all;
});
That way, {{personName}} would get the value from jsonObj.personName.
function createNewElement(jsonObj) {
var $clone = $('#message-template').clone();
$clone.html($clone.html().replace("{{person-name}}", jsonObj.personName));
$clone.html($clone.html().replace("{{thumb-url}}", jsonObj.thumbUrl));
$clone.html($clone.html().replace("{{person-url}}", jsonObj.personUrl));
// etc
$("#target-container").append($clone);
}

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