0

I want to remove everything except the img-element from the footer container:

<footer>
    <p>Some text</p>
    <img src="logo.jpg">
</footer>

In JQuery I would do this:

var logo = $('footer img');
$('footer').html(logo);

How do I do that in plain JS?

1
  • try using getElementByTagName.... Commented May 8, 2015 at 8:41

5 Answers 5

3

How about this?

  document.getElementsByTagName("footer")[0].innerHTML =  
            document.getElementsByTagName("img")[0]
Sign up to request clarification or add additional context in comments.

1 Comment

Is the innerHTML on the img element correct? I would assume you'd want the whole element and not only its contents.
2

Without recreating the original element, if you want

var footer = document.getElementsByTagName('footer')[0];
var img = footer.getElementsByTagName('img')[0];
footer.innerHTML = '';
footer.appendChild(img)

Demo: Fiddle

Comments

1

You could use the querySelector() function. It is exactly the same as jquery's selector function.

var logo = document.querySelector("footer img");
var footer = document.querySelector('footer');
footer.innerHTML = "";
footer.appendChild(logo);

More information about querySelector in W3Schools.

2 Comments

but I guess querySelector is slower then getElementsByTagName, isn't it?
Have a look at this: jsperf.com/…
1

That's not valid, you're setting the html of the footer to be the logo jQuery object? I think you mean the logo HTML.

You would do:

var footer = document.getElementsByTagName('footer')[0];
var logo = footer.getElementsByTagName('img')[0];

footer.innerHTML = logo.outerHTML;

1 Comment

@user3848987 Yep you're right, should be outerHTML I've fixed it :)
0

You can use this too:

var footer = document.querySelector("footer");
var replecedElement = document.querySelector("footer img");
footer.innerHTML = "";
footer.appendChild(replecedElement);

Demo: http://jsfiddle.net/t1qwn6bt/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.