Reputation: 2453
I would like the following text to appear as '"test test test'" using JavaScript.
<body>
<blockquote>test test test</blockquote>
</body>
I have the following code but it does not work
<blockquote window.onload = function test()> test test test</blockquote>
<script type="text/javascript">
function test(){
var a = document.getElementsByTagName(blockquote).value
return "a";
}
</script>
Upvotes: 0
Views: 2310
Reputation: 6541
The reason your code wont work is because getElementsByTagName returns a list of all the tags, not just one tag. So you need to manipulate the list (array).
I found Paulpro's answer helpful, but there are no explanations, so this might help someone.
var bqs = document.getElementsByTagName('blockquote');
Get a list of all the blockquote tags. Call that list bqs
for(var i = 0; i < bqs.length; i++)
Go through the list bqs once.And while you go down that list:
bqs[i].innerHTML = '"'+bqs[i].innerHTML+'"';
For each list item execute this code.
This code helps get from trying to execute on a list, to execute on all items on the list. The last line can be changed to do other things to the list like:
bqs[i].style.display = 'none';
Upvotes: 0
Reputation: 141877
One of these will work for you:
All blockquotes on the page when all HTML elements are in the DOM:
<blockquote>test test test</blockquote>
<blockquote>test2 test2 test2</blockquote>
<script type="text/javascript">
window.onload = function(){
var bqs = document.getElementsByTagName('blockquote');
for(var i = 0; i < bqs.length; i++)
bqs[i].innerHTML = '"'+bqs[i].innerHTML+'"';
}
</script>
<blockquote>test3 test3 test3</blockquote>
All blockquotes on the page above the script:
<blockquote>test test test</blockquote>
<blockquote>test2 test2 test2</blockquote>
<script type="text/javascript">
var bqs = document.getElementsByTagName('blockquote');
for(var i = 0; i < bqs.length; i++)
bqs[i].innerHTML = '"'+bqs[i].innerHTML+'"';
</script>
<blockquote>test3 test3 test3</blockquote>
Specific blockquote:
<blockquote id="wrapinquotes">test test test</blockquote>
<blockquote>test2 test2 test2</blockquote>
<script type="text/javascript">
var el = document.getElementById('wrapinquotes');
el.innerHTML = '"'+el.innerHTML+'"';
</script>
<blockquote>test3 test3 test3</blockquote>
Upvotes: 1
Reputation: 15579
shouldnt it be
<script type="text/javascript">
function test(){
var element = document.getElementsByTagName("blockquote")[0]; //getElementsByTagName returns an array
var attr = document.createAttribute('value');
attr.nodeValue = element .value; //code to set your value.. you need to escape double quotes..
element .setAttributeNode(attr);
}
</script>
<blockquote window.onload = function test()> test test test</blockquote>
if you are trying change the text in the between thr tag then you need to use the innerHTML property..
function test(){
var element = document.getElementsByTagName("blockquote");
element.innetHTML='"'+element[0].innerHTML+'"';
}
Upvotes: 0