Holden Chev
Holden Chev

Reputation: 109

Is there a concise way to change innerHTML of multiple divs within the same function?

I am replacing content of several divs using innerHTML when a button is clicked.

I currently have a new video source loading when a button is clicked but would also like to include changing a couple of other types of content in other divs on the same button click.

Firstly I wasn't sure if writing these functions one after the other (as in my included code snippets) would action all three correctly and secondly I was hoping they could all be piggy-backed within the same function somehow to simplify the coding.

I looked around for changing multiple HTML elements within one function but most innerHTML info that I could find only seems to addresses one element change.

//I currently have this:
$('#dog-video').on('click', function() {
  document.getElementById("video-content").innerHTML = '<source src= "dogvideo.mp4" type="video/mp4">';
video-content.load();
})

// But would also like to do both of these simultaneously
$('#dogvideo').on('click', function() {
  document.getElementById("h2-content").innerHTML = 'Dog Video Heading';
})

$('#dogvideo').on('click', function() {
  document.getElementById("p-content").innerHTML = 'This is dog text';
})

Upvotes: 0

Views: 480

Answers (1)

svidgen
svidgen

Reputation: 14302

There's nothing wrong with putting all three DOM updates in the same function body — or with using jquery within that function.

$('#dog-video').on('click', function() {
  $('#video-content').html('<source src= "dogvideo.mp4" type="video/mp4">');
  $('#h2-content').html('Dog Video Heading');
  $('#p-content').html('This is dog text');
  $('#video-content').load();
});

Upvotes: 2

Related Questions