How to wrap html text into spans with javascript - javascript

I want to wrap a text from html in a span so it should be like this
<p>Test yes</p>
into
<p><span>Test</span></p>
with javascript dom. Can anybody help me with this?

Try this.
document.getElementsByTagName("p")[0].innerHTML = '<span>' + document.getElementsByTagName("p")[0].innerHTML + '</span>';
<p>Test</p>

document.querySelectorAll("p").forEach(element => {
element.innerHTML = '<span>' + element.innerHTML + '</span>';
});
<p>Test1</p>
<p>Test2</p>
<p>Test3</p>
<p>Test4</p>

Not just text, in case you have some other html entities as well, inside the element like p tag here, here is what you can do :
var parent = document.querySelector("p");
parent.innerHTML = "<span>" + parent.innerHTML + "</span>"

Check out this snippet:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<p id="test_para">Test yes</p>
<script type="text/javascript">
var p = document.getElementById('test_para')
var span = document.createElement('span');
var node = document.createTextNode(p.innerHTML);
span.appendChild(node);
p.innerHTML = '';
p.appendChild(span);
</script>
</body>
</html>
In the snippet we did following things:
First we assigned id test_para to our paragraph. Through this id we locate it and store in variable p.
Second we create span element using createElement() method.
Third we create a text node using createTextNode() method and store text of our paragraph inside it.
Next we set add this node to span element we just created using appendChild() method.
Finally we make our paragraph empty and append newly created span element to it using appendChild() method.
There is another more less sophisticated way to do this:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<p id="test_para">Test yes</p>
<script type="text/javascript">
var p = document.getElementById('test_para')
p.innerHTML = '<span>'+p.innerHTML+'</spn>';
</script>
</body>
</html>
Here we locating our paragraph using id as we did in the snippet above. But rather than creating HTML elements using JavaScript, we just changing the HTML inside of our paragraph using its innerHTML property.

This, one line would do!
document.querySelectorAll("p").forEach(e => e.innerHTML = `<span>${e.innerHTML}</span>`)

Related

Adding text to an existing text element in JavaScript via DOM

I am trying to figure how to add text to a p tag or h1 tag that already has a text node.
For example:
var t = document.getElementById("p").textContent;
var y = document.createTextNode("This just got added");
t.appendChild(y);
<p id="p">This is some text</p>
This code gives an error appendChild is not a function. Most of the help pages first create a p tag and then append the text.
What is the right way to add text to an existing text element?
PS: I've used innerHTML before to do this, but for learning purposes I want to avoid it here.
The reason that appendChild is not a function is because you're executing it on the textContent of your p element.
You instead just need to select the paragraph itself, and then append your new text node to that:
var paragraph = document.getElementById("p");
var text = document.createTextNode("This just got added");
paragraph.appendChild(text);
<p id="p">This is some text</p>
However instead, if you like, you can just modify the text itself (rather than adding a new node):
var paragraph = document.getElementById("p");
paragraph.textContent += "This just got added";
<p id="p">This is some text</p>
Instead of appending element you can just do.
document.getElementById("p").textContent += " this has just been added";
document.getElementById("p").textContent += " this has just been added";
<p id ="p">This is some text</p>
The method .appendChild() is used to add a new element NOT add text to an existing element.
Example:
var p = document.createElement("p");
document.body.appendChild(p);
Reference: Mozilla Developer Network
The standard approach for this is using .innerHTML(). But if you want a alternate solution you could try using element.textContent.
Example:
document.getElementById("foo").textContent = "This is som text";
Reference: Mozilla Developer Network
How ever this is only supported in IE 9+
What about this.
var p = document.getElementById("p")
p.innerText = p.innerText+" And this is addon."
<p id ="p">This is some text</p>
remove .textContent from var t = document.getElementById("p").textContent;
var t = document.getElementById("p");
var y = document.createTextNode("This just got added");
t.appendChild(y);
<p id ="p">This is some text</p>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("p").append(" <b>Appended text</b>.");
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button id="btn1">Append text</button>
</body>
</html>
var t = document.getElementById("p").textContent;
var y = document.createTextNode("This just got added");
t.appendChild(y);
<p id="p">This is some text</p>

Remove placeholders using jQuery

I have the following code and I want to remove placeholder.
<div class="myclass">
<p>[Sitetile][change this too]someothercontent</p>
</div>
and I want to change the above markup to this with some event using jQuery:
<div class="otherclass">
<p>changemaincontentchangesomeothercontent</p>
</div>
Create an object with the index named as the part you want to replace (inside the brackets) and assign the value to it. Then use the $.each-function to iterate over the object and replace the values in the html with the one from the object. After that assign the new html-string to your element.
var change = {
'Sitename': 'yahoo.com',
'Sitetile': 'changemaincontent',
'change this too': 'change'
};
var $elem = $('.myclass > p'); //cache the element
var html =$elem.html(); //get the html-string
$.each(change, function(index, value){ //iterate over the object
html = html.replace('[' + index + ']', value); //replace the values
});
$elem.html(html); //assign the new html-string
Demo
Reference
.replace()
$.each()
.html()
you need to put someothercontent in <span>
HTML
<div class="myclass">
<p>
maincontent
<span>someothercontent</span>
</p>
</div>
Script
$('.myclass').find('a').text('changemaincontent');
$('.myclass').find('span').text('changesomeothercontent');
Demo
You can try some thing like this !!!
<<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id='link'><a href='javascript:open_fun()'>OPEN</a></div>
</body>
</html>
<script type="text/javascript">
function close_fun() {
document.getElementById('link').innerHTML = "<a href='javascript:open_fun()'>OPEN</a>";
}
function open_fun() {
document.getElementById('link').innerHTML = "<a href='javascript:close_fun()'>CLOSE</a>";
}
</script>
Hope this helps !!!

How to create an element in JavaScript, under a specific HTML tag

I want to create a paragraph element from JavaScript, but I want it to be placed under a certain tag in HTML. How would I do this?
Try with this.
var element = document.createElement("p"); //div,span,h1
element.appendChild(document.createTextNode('the text you want if you want'));
document.getElementById('theElementToAppend').appendChild(element);
<html>
<head>
<title>appendChild() Example</title>
<script type="text/javascript">
function appendMessage() {
var oNewP = document.createElement("p");
var oText = document.createTextNode("www.java2s.com");
oNewP.appendChild(oText);
document.body.appendChild(oNewP);
}
</script>
</head>
<body onload="appendMessage()">
</body>
</html>

How to get number of html elements in a string?

How to get number of HTML elements (HTML tags) in a string?
For example I have this string:
<div> some text
<div>
<label>some text</label>
</div>
</div>
Now how would I find number of html tags in this string? The result in the case above will be 3.
I did tried this, thought it will work but it didn't:
$('*').length;
var s = "<div> some text<div><label>some text</label></div></div>";
var length = $(s).find('*').andSelf().length;
http://jsfiddle.net/jCW7Z/
If you're using jQuery (and it looks like you are), the easiest way would be to use code similar to the following:
var count = $( yourString ).find('*').andSelf().length
However, if you're using vanilla javascript, the implementation would look more like this:
var temp = document.createElement('div');
temp.innerHTML = yourString;
var count = temp.getElementsByTagName('*').length;
Get all elements in the document (document.getElementsByTagName('*'))
Do a regular expression match on the element's className attribute for each element
You can use jQuery: $("html *") which will return all elements between the html tags
for names you must use $("html *").attr('name')
for values $("html *").val() or $("html *").attr('value')
Possible way to do it: http://api.jquery.com/length/
check out Find number of element in string with jQuery
for example
$( '.myClass', myData ).length;
(although this might not show outermost tags)
You can do it like this,
Put the string in to some hidden div like
$('#myHiddenDiv').html(string);
then
You can gen number of children under it
This will tell you number of html elements under the body
var count = $("#myHiddenDiv> *").length;
or:
var count = $("#myHiddenDiv").children().length;
Your div will be like this
<div id="myHiddenDiv" style="display:none"></div>
A small, self documenting, example :)
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>List Elements</title>
</head>
<body>
<div>some text
<div>
<label>some text</label>
</div>
</div>
<script>
var x=document.getElementsByTagName('*');
console.log(x.length)
for (i=0;i<x.length;i++) {
console.log(x[i]);
}
</script>
</body>
</html>

Inserting javascript global variable in <div> tag in HTML body

I have the following tag in HTML:
<div data-dojo-type="dojox.data.XmlStore"
data-dojo-props="url:'http://135.250.70.162:8081/eqmWS/services/eq/Equipment/All/6204/2', label:'text'"
data-dojo-id="bookStore3"></div>
I have the values 6204 and 2 in a couple of global variables in the script section:
<html>
<head>
<script>
...
var newNeId = gup('neId');
var newNeGroupId = gup('neGroupId');
...
</script>
</head>
</html>
Is it possible to have these variables in the div tag in the HTML body? If so, how?
To clarify this a bit more, I need to have the URL in the tag something like this:
url: 'http://135.250.70.162:8081/eqmWS/services/eq/Equipment/All/'+newNeGroupId+'/'+newNeId
I changed it according to your requirement:
<html>
<head>
<script type="text/javascript">
// example data
var newNeId = 10;
var newNeGroupId = 500;
window.onload = function(e){
var myDiv = document.getElementById("myDiv");
myDiv.setAttribute("data-dojo-props", "url:'http://135.250.70.162:8081/eqmWS/services/eq/Equipment/All/" + newNeId + "/" + newNeGroupId + "', label:'text'");
}
</script>
</head>
<body>
<div id="myDiv" data-dojo-type="dojox.data.XmlStore"
data-dojo-props="url:'http://135.250.70.162:8081/eqmWS/services/eq/Equipment/All/6204/2', label:'text'"
data-dojo-id="bookStore3"></div>
</body>
</html>​
You could add them to the <div> using the same datalist pattern (MDN docu) as Dojo:
<div id="savebox" data-newNeId="6204" data-newNeGroupId="2"></div>
These attributes are then accessible by the element.dataset.itemName.
var div = document.querySelector( '#savebox' );
// access
console.log( div.dataset.newNeId );
console.log( div.dataset.newNeGroupId );
As #EricFortis pointed out, the question remains, why you want to do this. This only makes sense, if you pass those values on from the server side.
Take one parent div then set its id and then you can rewrite whole div tag with attributes using innerHTML.
document.getElementById('id of parent div').innerHTml="<div data-dojo-type=/"dojox.data.XmlStore/"
data-dojo-props=/"url:'http://135.250.70.162:8081/eqmWS/services/eq/Equipment/All/6204/2', label:'text'/"
data-dojo-id=/"bookStore3/"></div>";
you can append values you wants in innerhtml now.
here's simple native js code to do it
var body = document.getElementsByTagName('body')[0];
var myDiv = document.createElement('div');
myDiv.setAttribute('id', 'myDiv');
var text = 'newNeId: ' + newNeId +
'<br/> newNeGroupId: ' + newNeGroupId';
body.appendChild(myDiv);
document.getElementById('myDiv').innerHTML = text;

Categories

Resources