Jump to content

JavaScript to know whether to use innerHTML or value


joe92

Recommended Posts

Does anyone know of a way that JavaScript could figure out whether it is to use .innerHTML or .value with a command?

 

I.e.

I have one function that is to change the contents of a group of elements within a for loop. I don't know whether the element that is currently being changed is going to be a div or a textarea so I would need to be able to figure out on the fly whether to use the .innerHTML or .value command with my function.

 

Thanks for any help,

Joe

Link to comment
Share on other sites

Changing the contents of a group of elements has to be triggered by something and that should tell you what is to be changed.

JS can't figure anything out, the programmer does this and controls js maybe with IF statements.

Looik at what ever is triggering the change and see if you can figure out what is to be changed. If you can't figure it out then post the code and we'll look at it.

 

Link to comment
Share on other sites

Got it sorted. When you locate the element on the page and then ask to display it, it will display something like [object HTML....Element]. By converting this into a string I could use the javascript match to look for which type of element it was and act accordingly. After looking at a list of every single tag available (and testing on tags I didn't know) I found that the only tags that actually need javascripts value to display on screen the contents are input tags and textareas. Here is my code should anyone run into a similar problem:

 

<?php
/*locate element*/
var element = document.getElementById(id);

/*turn [object HTML....Element] into a string that says just that*/
var el = new String(element);

/*match the string with value elements to produce value as the output*/
if(el.match(/Input/g) || el.match(/TextArea/g))
{
	/*fill the value*/
	element.value = thisItem;
}
/*since the huge majority of elements are actually filled using innerHTML, this is the else clause*/
else{
	/*fill innerHTML*/
	element.innerHTML = thisItem;
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.