var array = []; //In this i have 2 items
<div id="content"></div>
In this div id I need to pass the above array elements.
Ho can I do this?
Below is the basic example, how you interact with your DOM with javascript.
var array = [1, 2];
var content = document.getElementById("content");
for(var i=0; i< array.length;i++){
content.innerHTML += i + '--' + array[i] + '<br>';
}
<div id="content">
</div>
Big Note:
You can also use Javascript Templating if you are looking for passing a lot of other data as well to the View
You can use document.getElementById to get the id of the <div> and then insert the array as a string which will convert to the comma separated value:
var array = ['apple','ball']; //In this i have 2 items
document.getElementById('content').innerHTML = array.toString();
<div id="content"></div>
You Looking for Something like this ?
<div class="dummy" style="height: 100px;width: 100px;border: 1px solid black;"></div>
jQuery(document).ready(function(){
var arr = ['1','2'];
jQuery.each( arr, function( i, val ) {
jQuery('.dummy').append(val);
jQuery('.dummy').append("<br>");
});
});
jsfiddle : https://jsfiddle.net/vis143/c1kz0b8o/
Related
I have a html string and I need to remove all between first occurrence of <div class="c and first close tag > and last closing tag "</div>". The first, should be this because it class is dynamically generated.
For example: <div class="c2029" style="font-size:45px"><p class="auto">Testing 123...</p></div> should be transformed to <p class="auto">Testing 123...</p>
I tried this, but it's removing all string:
var testString = '<div class="c2029" style="font-size:45px"><p class="auto">Testing 123...</p></div>'
var result = testString.replace(/\<div\_c.*\>/, '');
The content into div that should be removed is dynamically generated, it is an example.
More examples of dynamic string generated:
var testString = '<div class="c03"><div style="text-align: center">Testing 123...</div></div>';
var testString = '<div class="c435">Hello</div>';
var testString = '<div class="c1980">TEST</div>';
No need to use regular expressions, you can achieve this with jQuery's $.fn.unwrap:
$('[class^="c"]').children().unwrap()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="c2029" style="font-size:45px">
<p class="auto">Testing 123...</p>
</div>
To make it more bullet proof and target only element with class staring with "c" and with numbers after you could add additional filtering step:
$('[class^="c"]').filter(function () {
return this.className.match(/\bc\d+\b/)
}).children().unwrap()
This way it will not affect classes like cello (starts with "c").
Regex is wrong tool for this. You can just $.parseHTML() and then find() using [name^=”value”] selector and use it:
var all = ['<div><div class="c2029" style="font-size:45px"><p class="auto">Testing 123...</p></div></div>', '<div><div class="c435">Hello</div></div>', '<div><div class="c1980">TEST</div></div>'];
$.each(all, function(k,s) { f(s); });
function f(s) {
var nodes = $($.parseHTML(s)); // parse string to jquery object
var $p = nodes.find('div[class^="c"]'); // select all classes that starts with c
var inner = $p.prop('innerHTML'); // inner html of $p
console.log("Inner: " + inner);
$p.html(''); // select children of $p and remove
var outer = $p.prop('outerHTML'); // outer html of $p
console.log("Outer: " + outer);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Based on Stack Overflow answers, I found this solution that resolve my problem:
var testString = '<div class="c2029" style="font-size:45px"><p class="auto">Testing 123...</p></div>'
var result = testString.replace(/<div class="c.*?>(.*?)<\/div>/, '$1');
document.write(result);
console.log(result);
I have use this following technique to replace sting in html.
var str = "Some html values";
var res = str.replace("{company}","Microsoft");
But i want to loop div like angular js by using pure JavaScript like shown below
{foreach value in values} <div class="test">{value}</div> {/foreach}
if anyone knows please let me know
Here is a way in vanilla JS :
var values = ["Microsoft", "Apple", "Amazon"];
var node = document.getElementById( "myDiv" );
var res="";
for (id in values){
res+="<p>"+values[id]+"</p>";
}
node.innerHTML=res;
<div id='myDiv'></div>
I have found the solution
var values = '';
var alphabet = ['a','b','c','d','e'];
var meanings = ['apple','banana','choclate','dominoes pizza','eggs']
var value = document.getElementById("test1").innerHTML;
for (var i=0; i<alphabet.length; i++) {
values += value.replace("{value}",alphabet[i]).replace("{meanings}",meanings[i]);
}
document.getElementById("test2").innerHTML = values;
<div id="test2" class="test">
<div id="test1" class="test">
<div class="test">
{value} for {meanings}
</div>
</div>
</div>
Is there any way to check if two divs are having same ids?
I have created divs dynamically and I am finding it difficult to remove the div having a duplicate id, can anyone help here?
I do not know what you are trying to achieve here , but generally you should not have two elements with the same id . But if you have some reason to do this maybe you are building a validator or someting like this you can do the following to count the number of elements
var count = document.querySelectorAll('#test').length;
console.log(count);
then you can loop through them and remove them using
document.querySelectorAll('#test')[1].remove();
Try it with:
$('[id]').each(function () {
var ids = $('[id=' + this.id + ']');
if (ids.length > 1 && ids[0] == this) {
$(ids[1]).remove();
}
});
You have to loop all the elements as helpers like getElementById() won't work well when their aren't unique.
Example, no need for jQuery. Alerts the duplicate ID.
var idMap = {};
var all = document.getElementsByTagName("*");
for (var i=0; i < all.length; i++) {
// Do something with the element here
var elem = all[i];
if(elem.id != ""){ //skip without id
if(idMap[elem.id]){
alert("'" + elem.id + "' is not unique")
}
idMap[elem.id] = true;
}
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
</head>
<body>
<div id="id1"></div>
<div id="id2"></div>
<div id="id3"></div>
<div id="id4"></div>
<div id="id5"></div>
<div id="id1"></div>
</body>
</html>
var idList = [];
$('*[id]').each(function(){
var id = $(this).attr('id');
if($.inArray(id, idList)){
alert('the id ' + id + ' is already set!');
} else {
idList.push(id);
}
});
$('[id]').each(function(){
var ids = $('[id="'+this.id+'"]');
if (ids.length>1 && ids[0]==this){
$("#"+this.id).remove();
}
});
above function use jquery to create array of all IDs with in the document and remove duplicated id
Something like this should do what you want
$('[id]').each(function (i) {
$('[id="' + this.id + '"]').slice(1).remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "1">
ola
</div>
<div id = "2">
ole
</div>
<div id = "1">
ola
</div>
<div id = "3">
olo
</div>
<div id = "1">
ola
</div>
<div id = "3">
olo
</div>
Example based on the link: jQuery: Finding duplicate ID's and removing all but the first
Can you not just control + F and search for the id's? Also if you are using an editor like atom, you can delete every other duplicate in one go after the search.
Hello i have a class with elements
<div class="help_1"></div>
<div class="onemoreclass help_2 twoclass"></div>
<div class="test help_3"></div>
<div class="class1 help_4"></div>
how can i extract only help_(*) matches with javascript?
for straight javascript working against the attribute class (assuming you're not using jQuery and can locate the elements in question via DOM)
// Contains array of matches or null if none found
var matches= classAttr.match(/(help_\w)/g);
This solution requires the jQuery library:
var A = [];
$('div').each(function(){
var B = $(this).attr('class').split(' ');
for(var i=0;i<B.length;i++){
var C = B[i];
if( /^help_/.test(C) ){
A.push(C);
}
}
});
console.log(A);
I have following html:
<div id="note">
<textarea id="textid" class="textclass">Text</textarea>
</div>
How can I get textarea element? I can't use document.getElementById("textid") for it
I'm doing it like this now:
var note = document.getElementById("note");
var notetext = note.querySelector('#textid');
but it doesn't work in IE(8)
How else I can do it? jQuery is ok
Thanks
If jQuery is okay, you can use find(). It's basically equivalent to the way you are doing it right now.
$('#note').find('#textid');
You can also use jQuery selectors to basically achieve the same thing:
$('#note #textid');
Using these methods to get something that already has an ID is kind of strange, but I'm supplying these assuming it's not really how you plan on using it.
On a side note, you should know ID's should be unique in your webpage. If you plan on having multiple elements with the same "ID" consider using a specific class name.
Update 2020.03.10
It's a breeze to use native JS for this:
document.querySelector('#note #textid');
If you want to first find #note then #textid you have to check the first querySelector result. If it fails to match, chaining is no longer possible :(
var parent = document.querySelector('#note');
var child = parent ? parent.querySelector('#textid') : null;
Here is a pure JavaScript solution (without jQuery)
var _Utils = function ()
{
this.findChildById = function (element, childID, isSearchInnerDescendant) // isSearchInnerDescendant <= true for search in inner childern
{
var retElement = null;
var lstChildren = isSearchInnerDescendant ? Utils.getAllDescendant(element) : element.childNodes;
for (var i = 0; i < lstChildren.length; i++)
{
if (lstChildren[i].id == childID)
{
retElement = lstChildren[i];
break;
}
}
return retElement;
}
this.getAllDescendant = function (element, lstChildrenNodes)
{
lstChildrenNodes = lstChildrenNodes ? lstChildrenNodes : [];
var lstChildren = element.childNodes;
for (var i = 0; i < lstChildren.length; i++)
{
if (lstChildren[i].nodeType == 1) // 1 is 'ELEMENT_NODE'
{
lstChildrenNodes.push(lstChildren[i]);
lstChildrenNodes = Utils.getAllDescendant(lstChildren[i], lstChildrenNodes);
}
}
return lstChildrenNodes;
}
}
var Utils = new _Utils;
Example of use:
var myDiv = document.createElement("div");
myDiv.innerHTML = "<table id='tableToolbar'>" +
"<tr>" +
"<td>" +
"<div id='divIdToSearch'>" +
"</div>" +
"</td>" +
"</tr>" +
"</table>";
var divToSearch = Utils.findChildById(myDiv, "divIdToSearch", true);
(Dwell in atom)
<div id="note">
<textarea id="textid" class="textclass">Text</textarea>
</div>
<script type="text/javascript">
var note = document.getElementById('textid').value;
alert(note);
</script>
Using jQuery
$('#note textarea');
or just
$('#textid');
$(selectedDOM).find();
function looking for all dom objects inside the selected DOM.
i.e.
<div id="mainDiv">
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<div id="innerDiv">
link
<p>Paragraph 3</p>
</div>
</div>
here if you write;
$("#mainDiv").find("p");
you will get tree p elements together. On the other side,
$("#mainDiv").children("p");
Function searching in the just children DOMs of the selected DOM object. So, by this code you will get just paragraph 1 and paragraph 2. It is so beneficial to prevent browser doing unnecessary progress.