Change tag using javascript [duplicate] - javascript

This question already has answers here:
Can I change an HTML element's type?
(9 answers)
Closed 4 years ago.
I want to know how can I change a tag with pure javascript like that
<span>some text</span>
I want to change it to that
<div>some text</div>
I have no idea how to do it.

You can't change the type of an element like that, instead you have to create a new element and move the contents into it. Example:
var e = document.getElementsByTagName('span')[0];
var d = document.createElement('div');
d.innerHTML = e.innerHTML;
e.parentNode.replaceChild(d, e);
Demo: http://jsfiddle.net/Guffa/bhnWR/

Just written a jQuery plugin for this.
(function( $ ) {
$.fn.replaceTag = function(newTag) {
var originalElement = this[0]
, originalTag = originalElement.tagName
, startRX = new RegExp('^<'+originalTag, 'i')
, endRX = new RegExp(originalTag+'>$', 'i')
, startSubst = '<'+newTag
, endSubst = newTag+'>'
, newHTML = originalElement.outerHTML
.replace(startRX, startSubst)
.replace(endRX, endSubst);
this.replaceWith(newHTML);
};
})(jQuery);
Usage:
$('div#toChange').replaceTag('span')
The biggest advantage of this method is that id preserves all the attributes of the original element.

If jquery is acceptable use replaceWith.
$('span').each(function() {
$(this).replaceWith($('<div>' + this.innerHTML + '</div>'));
});
Here is a JSFIDDLE working DEMO

If using jquery
Var spantxt = $('span').text();
$('body').append('<div>'+spantext+'</div');
Note this would only work if there was only one span, use an id selector otherwise

You can't do it.
What you want to do is to take content of your span,
then delete it and create new div and fill it with previous content.

Assumption: The span you want to replace is wrapped in a div with id "foo"
In pure javascript you could do something like:
var original_html = document.getElementById('foo').innerHTML;
original_html = original_html.replace("<span>", "<div>");
original_html = original_html.replace(new RegExp("</span>"+$), "</div">)
document.getElementById('foo').innerHTML=original_html;
If however you can not necessarily expect the span to be tightly wrapped by an element you can consistently get (by id or otherwise), the javascript becomes fairly complex. In either case, the real answer here is: use jQuery.

Related

How to get element(tag) inner text in pure js

I have a string named stringElement and its value is anchor tag but in string not as node element.
How to get the inner text of that tag in pure js?
How it was done using jQuery:
var stringElement = "<a>1</a>";
nodeElement div = document.createElement('div');
$(div).append(stringElement);
var nodeElement2 = $(div).find("a")[0];
var text = $(nodeElement2).text();
text value is 1 <=== This is the target
EDIT: My bad, I found the answer in another question and this should be marked as duplicate.
Here is the questions link:
Converting HTML string into DOM elements?
Here is the answer link that worked for me:
https://stackoverflow.com/a/3104237/2648837
try this,usetextContent or innerText
var str = "<a>1</a>";
var div=document.createElement('div');
div.innerHTML=str;
console.log(div.children[0].textContent);
console.log(div.children[0].innerText);

Javascript element html without children [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
In my javascript code I need to get the definition of an element, but without its content - neither text nor children.
E.g. for:
<div id="my_example_id" class="ShinyClass">
My important text
<span> Here</span>
</div>
I would like to write a javascript fucntion that when provided with the element of the div above will return the following as string:
<div id="my_example_id" class="ShinyClass">
I have been trying with different manipulations over the elements, functions like innerHTML, outerHTML and similar, but I was unable to figure out how to fetch only the part I am interested in. Is substring until the first > the best possible solution?
EDIT: selecting the element is not part of the question - I know how to do that, no prob. Rather the question is: when I have already selected a particular element how to parse as string only its own definition.
UPDATE:
const div = document.getElementById('my_example_id'); // get the node
const html = div.outerHTML.replace(div.innerHTML || '', ''); // simple set logic
console.log(html);
Just some way to do this, not saying the best.
const div = document.getElementById('my_example_id');
const copy = div.cloneNode(true);
const parent = document.createElement('div');
copy.innerHTML = '';
parent.appendChild(copy); // I forgot to add this line.
const html = parent.innerHTML;
console.log(html);
Basically you create a copy of the div, create a parent, then remove innerHTML of the copied node to leave out just the 'div' itself. Append the copied node to the new parent and show the parent's innerHTML which is just the 'div' you wanted.
you don't need to do all that fancy stuff copying it to a parent..
// make a copy of the element
var clone = document.getElementById('my_example_id').cloneNode(true);
// empty all the contents of the copy
clone.innerHTML = "";
// get the outer html of the copy
var definition = clone.outerHTML;
console.log(definition);
I threw it in a function in this fiddle: https://jsfiddle.net/vtgx3790/1/
I guess that a Regex is what you need. Check if this works for you
function getHtml(selector) {
var element = document.querySelector(selector)
var htmlText = element.outerHTML
var start = htmlText.search(/</)
var end = htmlText.search(/>/)
return htmlText.substr(start, end + 1)
}
alert(getHtml('.ShinyClass'))
example here
console.log(getElementTag("my_example_id"));
function getElementTag(myElementId) {
var FullEelementObject = document.getElementById(myElementId);
var FullElementText = FullEelementObject.outerHTML;
var regExTag = new RegExp(/(<).*(>)/i);
openingTag = FullElementText.match(regExTag);
return openingTag[0];
}
Just threw together this JSFiddle, it gets the outerHTML of the element you pass the function, the regExp to get the full opening tag.
Edit: Here is the JSFiddle

Change from getElementById to getElementsByClassName [duplicate]

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 7 years ago.
Hi i got a script like this:
$(".news-button").click(function(){
var img = document.getElementById('news-image').src;
if (img.indexOf('news-bt-1.png')!=-1) {
document.getElementById('news-image').src = 'img/news-bt-2.png';
}
else {
document.getElementById('news-image').src = 'img/news-bt-1.png';
}
});
It worked fine but now i want to change news-image from id to class so how to change the code above?
You can use getElementsByClassName instead getElementById
You can use getElementsByClassName and select the first element, because this method returns a list of Elements which is ordered by the position of the elements in the DOM.
So, given that the element you want to get is the first one that appears in your HTML code with that class, you can do:
document.getElementsByClassName("news-image")[0]
And if it isn't the first one, you can change the number and select another element:
document.getElementsByClassName("news-image")[2] // third element
You can also use querySelector to select the first element that matches the given CSS selector, which is, in my opinion, easier:
document.querySelector("img.news-image")
Finally, since I see you're using jQuery as well, you can use it's selector like this:
$("img.news-image")[0]
Talking about your specific code, here's the solution you were looking for:
$(".news-button").click(function(){
var img = $('img.news-image')[0];
if (img.src.indexOf('news-bt-1.png')!=-1) {
img.src = 'img/news-bt-2.png';
}
else {
img.src = 'img/news-bt-1.png';
}
});
You can use
var elements = document.getElementsByClassName(classname)
It will get you all the elements matched as an array. So first make sure you got the array, then access the elements like elements[index]
Use :-
document.getElementsByClassName('news-image')[0].src
Since getElementsByClassName returns array you need to use index of it.
But as i can see you are using jquery on click event then why you are using javascript inside it instead use jquery inside it will help you in cross-platform
$(".news-image").each( function() {
var img= $(this).attr('src');
if (img.indexOf('news-bt-1.png')!=-1) {
$(this).attr('src','img/news-bt-2.png')
}else{
$(this).attr('src','img/news-bt-1.png')
}
});
Use the below code, just Replace className with the actual class name of you tag img :
$(".news-button").click(function () {
var img = document.getElementById('news-image').src;
var img1 = document.getElementsByClassName("className");
if (img.indexOf('news-bt-1.png') != -1) {
img1.src = 'img/news-bt-2.png';
}
else {
img1.src = 'img/news-bt-1.png';
}
});
You can use Jquery as well.
To get source of image:
$('.classname').attr('src')

Find DOM element in text content using javascript

Please push me towards a duplicate of this question if possible. I've looked everywhere but can't seem to find it.
How do I do a getElementById on text content?
var test = '<div id="thisDiv">HI</div>';
How do I select thisDiv if it's not a part of the DOM?
Create an element, set your string as its innerHTML and then search inside that ...
Something like
var test = '<div id="thisDiv">HI</div>';
var element = document.createElement('DIV');
element.innerHTML = test;
alert(element.textContent);
(changed the initial outerHTML as you can only maintain a reference to the originaly created element, and not the new one that is created by the new html)
For getting the text value inside your tags, use RegEx:
var re = new RegExp("<(.|\n)*?>", "g");
var content = test.replace(re,"");
You could create a temporary DIV and populate it with your string. Even then, your ability to access it would be limited. Add it to the DOM to access it using getElementById.
var div = document.createElement('div');
div.innerHTML = '<div id="thisDiv">HI</div>';
alert(div.firstChild);
To avoid creating that extra element, we could just add it to the body...
var test = '<div id="thisDiv">HI</div>';
document.querySelector('body').innerHTML = test;
console.log(document.getElementById('thisDiv'));
Obligatory Fiddle
Getting just the text...
console.log(document.getElementById('thisDiv').textContent); // returns HI

Trying to .replace() Without Success

I have some lines of HTML code that are like this:
<li>Testing jQuery [First Bracket]</li>
<li>Loving jQuery [Second one]</li>
I'm trying to replace what's inside the bracket with nothing onLoad, like this:
var item = $(".lstItem").text();
var match = item.match(/\[(.*?)\]/);
item = item.replace(match[0], "");
But nothing changes. What's wrong and how to correct this?
After using jimbojw's suggestion I'm getting a Uncaught ReferenceError: text is not defined at this particular line:
oldtext = $item.text,
item is a variable containing a string, not a pointer to the literal text. If you want to change the text, you have to set it again, vis a vis $(".listItem").text(item)
edit - predicting next problem
The next problem you're going to have is that all the text gets set to the same thing. So what you really want to do is probably something like this:
$(".lstItem")
.each(function(index, item) {
var
$item = $(item),
oldtext = $item.text(),
match = oldtext.match(/\[(.*?)\]/),
newtext = oldtext.replace(match[0], '');
$item.text(newtext);
});
this will do the job for you:
you are splitting your code in too much lines, also your need to run replace for each individual element separately.
$(".lstItem").each(function() {
$(this).html(
$(this).html().replace(/\[(.*)\]/, "")
);
});
see your example in jsFiddle: http://jsfiddle.net/eKn3Q/7/
Along with jimbojw's answer $(".lstItem").text() will retrieve all the text inside of your <a/> elements. One way to handle this would be to pass a function(i,t){} into the .text() method.
$(".lstItem").text(function(i, text){
var match = text.match(/\[(.*?)\]/);
return text.replace(match[0], "");
});
Simple example on jsfiddle
also your regex could be simpler.
var item = $(".lstItem").text();
var match = /\[(.*?)\]/;
$(".listItem").text(item.replace(match,""));

Categories