Remove placeholders using jQuery - javascript

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 !!!

Related

How to wrap html text into spans with 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>`)

Extract element by ID from string?

I have a string which contains this text:
<!DOCTYPE html>
<html>
<head>
<title>ExtractDiv test</title>
</head>
<body>
<p>Apples and oranges</p>
<div id="main">
<ul style="list-style-type: upper-roman">
<li>Äpfel</li>
<li>Birnen</li>
</ul>
</div>
<p>Men and women</p>
</body>
</html>
Now I need a JavaScript function which gives me back a DOM element with a specific ID as a string from this text, for example:
function ExtractElementByIdFromString(HTMLString, IdString)
{
var ExtractedElement = ???(HTMLString, IdString);
return ExtractedElement;
}
So the RESULT of this function in this case would be:
<div id="main">
<ul style="list-style-type: upper-roman">
<li>Äpfel</li>
<li>Birnen</li>
</ul>
</div>
Is this possible?
You can parse an HTML string with the native DOMParser:
var str = "<!DOCTYPE……………" // your HTML string
var doc = new DOMParser().parseFromString(str, "text/html")
Then just use regular DOM methods:
console.log( doc.getElementById("main") )
Note that using a DOMParser is more efficient and safer than inserting the string somewhere in your document's innerHTML, because only the structure will be created — <script> elements won't be executed, images won't be loaded, CSS will no try to apply to it, no rendering will occur, etc.
You can create a temporary element, put the HTMLString as a content to it, then use querySelector to get an element with passed id. Something like this:
function ExtractElementByIdFromString(HTMLString, IdString) {
var result,
temp = document.createElement('div'); // Create a temporary element
temp.innerHTML = HTMLString; // Set the passed string as HTML to the temporary element
result = temp.querySelector('#' + IdString).outerHTML; // Find an element with the passed id
return result;
}
A working demo at jsFiddle.

Return value from javascript to html

<head>
function productName(name)
{
}
</head>
<body>
<img src="...images/car.jpg" onclick="productName('car')">
</body>
What I should write in this javascript function to print the value received from the onclick method to any public place in my html body?
Say you have an element like this:
<div id="content">
</div>
your js function would be like this:
<script type="text/javascript">
function productName(name)
{
document.getElementById('content').innerHTML = name;
}
</script>
You can create a textNode and append it to the body
function productName(name) {
var t=document.createTextNode(name);
document.body.appendChild(t)
}
Demo: Fiddle
Or in jQuery,
$('#content').html( name); // inner HTML of an element, by ID
$('#inputField').val( name); // into an INPUT.

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