I have a page that generates the following code (example):
<div class="map_object">
<span> test1 </span>
<script></script>
</div>
<div class="map_object">
<span> test2 </span>
<script></script>
</div>
<div class="map_object">
<span> test3 </span>
<script></script>
</div>
These blocks are created by a html template file. The row with the <span>
comes in by a placeholder (users can enter this into a text field), the rest is in the template file.
What i need is to get the content inside the <span>
in every <script>
(always the exact same script) Let's say block 1 should return "test1" an so on.
Do you have any idea, how to find the current <script>
and then get the content in the <span>
before, so this works for every block and not just the first or last one?
Not sure what you want..
This is pure javascript solution: DEMO
window.onload=function(){
var span = document.getElementsByTagName("span");
for(var i=0;i<span.length;i++)
{
span[i].nextElementSibling.innerHTML = span[i].innerHTML
}
};
OUTPUT:
<body>
<div class="map_object">
<span> test1 </span>
<script> test1 </script>
</div>
<div class="map_object">
<span> test2 </span>
<script> test2 </script>
</div>
<div class="map_object">
<span> test3 </span>
<script> test3 </script>
</div>
Have done this with jquery DEMO
$(function(){
$('span').each(function(){
$(this).next('script').text($(this).text());
});
})
Output:
<div class="map_object">
<span> test1 </span>
<script> test1 </script>
</div>
<div class="map_object">
<span> test2 </span>
<script> test2 </script>
</div>
<div class="map_object">
<span> test3 </span>
<script> test3 </script>
</div>
Note: If this is what you what then we can do this with javascript also
Not the cleanest of solutions, but then again, also not the cleanest of questions:
<div class="map_object">
<span> test1 </span>
<script>
alert(document.currentScript.parentNode.getElementsByTagName('span')[0].innerHTML)
</script>
</div>
Fiddle here .
To clarify a bit more:
<div class="map_object">
<span> test1 </span>
<script>
var scriptElement = document.currentScript;
var divElement = scriptElement.parentNode;
var firstSpanElement = divElement.getElementsByTagName('span');
alert(firstSpanElement.innerHTML)
</script>
</div>
You can try this, using Jquery.
<script>
$(document).ready(function(){
var values= $(".map_object > span");//Get spans
$.each(values, function( index, value ) {
console.log(value.innerHTML);//get every span content
});
});
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.