How to insert a js array into html using innerHTML? - innerhtml

In order to build a more clean code, i would like to delete an unordered list from html file and insert instead a js array using innerHTML. The problem is that i am new to html/css/js and I have a lot of difficulties in typing the correct syntax and understanding the logic.
In my html file i had a div with id="listOfBeaches "containing a list with beaches. if i delete the ul and I try to insert instead a js array i don't get any result.
<div id="listOfBeaches">
<ul>
<li><h3>Horseshoe Bay</h3></li>
<li><h3>Trunk BAy</h3></li>
<li><h3>El Nido</h3></li>
<li><h3>Reethi Rah</h3></li>
<li><h3>Maundays Bay</h3></li>
</ul>
</div>
I try to replace this html code with the following js code
let beaches= [
{
name: 'Horseshoe Bay',
url: './Horseshoe.html',
},
{
nume: 'Trunk BAy',
url: './Trunk-bay.html',
},
{
name: 'El Nido',
url: './El-Nido.html'
},
{
name: 'Reethi Rah',
url: './Rheeti-Rah.html'
},
{
name: 'Maundays Bay',
url: './Maundays-BAy.html'
}
];
let myBeaches = '';
for (let i = 0; i < beaches.length; i++){
myBeaches = beaches[i].name;
}
document.getElementById('listOfBeaches').innerHTML(myBeaches);
The result should be a list of beaches at the top of my webpage
Can I get any help from you guys?

If you were to look at the output of document.getElementById('listOfBeaches').innnerHTML you would see that it would contain
<ul>
<li><h3>Horseshoe Bay</h3></li>
<li><h3>Trunk BAy</h3></li>
<li><h3>El Nido</h3></li>
<li><h3>Reethi Rah</h3></li>
<li><h3>Maundays Bay</h3></li>
</ul>
So as such, you'll need to build up a similar html entry if you want to replace it using the innerHtml method. You could do something as such:
https://jsfiddle.net/nshe1qL8/

Related

VueJS2: How to pluck out one property of an array and use it to find matching value in the second array?

I have two arrays. I am trying to pluck out a property from one array and use it to find the value of another property in the other way. How to do this? Let me explain:
I have an array of objects that looks like so:
languageCodes:
{
"code1234char3": "mdr",
"name": "Mandar",
},
{
"code1234char3": "man",
"name": "Mandingo",
},
{
// etc...
},
I have another array of objects that looks like so:
divisionLanguages:
[
{
p_uID: 1,
nameLang3Char: 'mdr',
},
{
p_uID: 2,
nameLang3Char: 'man'
},
{
// etc..
}
]
I have a Vue template with an unordered list like so:
<ul v-for="x in divisionLanguages" :key="x.p_uID">
<li>Name: FOO
<li>Language: {{x.nameLang3Char}} - XXX</li> <--how to get 'name' value from 'languageCodes' and place here?
</ul>
Expected output should be:
Name: FOO
Language: mdr - Mandar
Name: BAR
Language: man - Mandingo
I tried to do something like in Vue SFC template (but did not work):
<li>Language: {{ languageName(x.nameLanguage3Char) }}</li>
...
methods: {
languageName(nameLanguage3Char) {
const name = this.divisionLanguages.filter(x => x.code6392char3 === nameLanguage3Char)
return name.name
}
I hope this makes sense of what I am trying to do.
Update: Thanks to #kellen in the comments, I change from filte() to find() like so:
languageName(nameLang3Char) {
const languageName = this.languageCodes.find(
x => x.code1234char3 == nameLang3Char
)
return languageName
},
and in I did:
<li>Language: {{ languageName(x.nameLang3Char).name }}</li>
and it works...but I get error in console:
Error in render: "TypeError: Cannot read property 'name' of undefined"
Have you tried combining these arrays before rendering them? If you were able to combine both objects before creating that list, that would make your life easier. Another thing I noticed is you're using filter, when find might be a better option to return a single value rather than an array. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

Get multiple values from array fetch

I am sending a get request to a api where the values are inside a array.
I want to get multiple values simultaneously.
How can I do this other than using index to get specific key values?
For example below, I want every result of results.data.message.body.artist_list.[4].artist.artist_name but don't want to have to use index [4].
methods: {
fetchMusic(e) {
if (e.key === 'Enter') {
// eslint-disable-next-line no-undef
axios.get(' ... ', {
headers: {
'Access-Control-Allow-Origin': '*',
},
})
.then((response) => response).then(this.setResults);
}
},
setResults(results) {
this.artists = results.data.message.body.artist_list.[4].artist.artist_name;
this.artistname = results.data.message.body.artist_list[0].artist.artist_name;
},
},
};
</script>
Thanks for any inputs on my code
Here is an example on how to fetch an API and display it's info by looping on the items: https://codesandbox.io/s/lucid-currying-nsoo3?file=/src/App.vue
Basically, get the results (an array so), then loop on each iteration of this array and display the wished data accordingly with something like
<div v-for="result in fetchedResults" :key="result.id">
<p>
<span>Name: {{ result.username }}</span> ~
<span>email: {{ result.email }}</span>
</p>
</div>
Btw, don't forget the key, it's important. More info here about this point.
Official documentation's examples on how to loop on an array.

WebdriverIO: what is the equivalent of elementIdHtml?

How do I get an element's inner HTML from an elementId using browser object?
Is there something like elementIdHtml available in the WebdriverIO API?
The getHTML link for v4 is returning 403 Forbidden.
my goal is that i need to get all text inside all a._3cnp from an elementId
example html
<div class="container">
<a class="_3cnp">first link</a>
<a class="_3cnp">second link</a>
<a class="_3cnp">third link</a>
</div>
need to convert that to ["first link", "second link", ..]
i have the .container elementId already
this is what i did
.then(() => browser.elementIdElements(someElementId, 'a._3cnp'))
.then(buttonElem => {
console.log('->', buttonElem)
console.log('-->', buttonElem.getHTML)
buttonElem.getHTML().then(x => console.log('---->', x))
return buttonElem.value
})
result of elementIdElements is
buttonElem
{ sessionId: '2e2f144c8895a03da1b8df92f4613a33',
status: 0,
value:
[ { ELEMENT: '0.6603119466268468-24',
'element-6066-11e4-a52e-4f735466cecf': '0.6603119466268468-24' } ],
selector: 'a._3cnp' }
but buttonElem.getHTML is undefined
im using webdriverio standalone from botium-webdriverio-connector
LE:
Change your code accordingly to the following:
.then(() => browser.elementIdElements(someElementId, 'a._3cnp'))
.then(buttonElem => {
// buttonElem's 'value' will contain a list of all the matching elements
// thus, you have to call getHTML() on each item from 'value'
// the following will return the HTML of the first matching element
console.log('\nPrint element HTML: ' + buttonElem.value[0].getHTML());
return buttonElem.value[0].getHTML();
})
A better approach would be to loop between them & print the HTML:
.then(() => browser.elementIdElements(someElementId, 'a._3cnp'))
.value.forEach(buttonElem => {
console.log('\nPrint element HTML: ' + buttonElem.getHTML());
return buttonElem.getHTML();
})
The .getHTML() property is scoped to all the ELEMENT objects. For the sake of more didactical approach, I'm going to consider the task to be manipulating the HTML code found in a series of list items (<li>), from am unordered list (<ul>).
So you can do the following:
browser.getHTML('ul.ourList li.ourListItems') (this will return a list of all the <li>'s HTML code)
browser.element('ul.ourList li.ourListItems').getHTML() (this will return the first <li>'s HTML code)
$('ul.ourList li.ourListItems').getHTML() (this is the equivalent of the command above, only a relaxed version)
If you need to iterate through all the <li>s & get the HTML, do this:
let locator = 'ul.ourList li.ourListItems';
browser.elements(locator).value.forEach(elem => {
let elemHTML = elem.getHTML();
console.log( JSON.stringify(elemHTML) );
elemHTML.doSomethingWithIt();
})
where, elem will is an object with the following format:
{ ELEMENT: '0.285350058261731-1',
'element-6066-11e4-a52e-4f735466cecf': '0.285350058261731-1',
selector: 'ul li.fw-item.fz-16.lh-36.pos-r',
value: { ELEMENT: '0.285350058261731-1' },
index: 0
}

jquery .map is not working on IE 10

I have this jquery code:
$("#tf_zoom").live("click", function () {
var n = $(".tf_thumbs").find("img").attr("src");
var modelid = n.substr(43);
$.post("models/get_gallery", {
"modelid": modelid
}, function (data) {
var imagespathes = $(data).map(function (key, url) {
return ({
href: '<?php echo base_url();?>assets/uploads/files/' + url
});
});
console.log(imagespathes);
$.fancybox.open(imagespathes);
}, "json");
});
and this is my html:
<div id="tf_thumbs" class="tf_thumbs">
<span id="tf_zoom" class="tf_zoom"></span>
<img id="dynam" src="<?php echo base_url();?>assets/uploads/files/<?php echo $firstthumb;?>" alt="Thumb1"/>
</div>
Okay, now my problem is that this code is not functioning on IE 10 and surprisingly it's working like a charm on IE 9, IE 8, IE 7 besides FF and Google Chrome
I read many things about this issue but nothing worked for me.
So, is there any solution for it.
your help is really appreciated.
Update 1 : I am using jquery version 1.7
Perhaps this hint will help you:
I have noticed that .map( $("select").get(0).options ) will not work in IE10 but .map( $("select:first >option") ) will. This is because in ie10 .options returns a select node with an iteration of options.
So see what data is returning in IE10, perhaps it too is not an array. And if so perhaps you can do something like $(new Array(data)).map(... which will satisfy all browsers
You should be using static map function for this:
$.map(data, function(obj, index){...})
See documentation here.
// If data looks like this: [{ url: 'TestUrl' }]
// This should work:
var imagespathes = $.map(data, function(element){
return { href: '<?php echo base_url();?>assets/uploads/files/' + element.url };
});

dojo1.8 - tried to register but . . . already registered - building select widget

Hi I had a trouble figuring out where select's id is registered at attempted once more.
Possible causes:-
1) ParseOnload and Parser.parse() on the same page
2) Giving the same id to another new select
3) Registering the same select with new id
I could not figure what cause the select to registered twice.
...
...
<div id='main_bContainer' data-dojo-type='dijit/layout/BorderContainer' data-dojo-props='design:"sidebar"'>
<div id='paneA' class='cP_Left' data-dojo-type='dijit/layout/ContentPane' data-dojo-props='region:"left"'>
<div id='surfaceElement1' style='border:1px solid #ccc; margin-bottom:5px; width:317px; height:55px;'><!--these dimensions here in this line override the dimensions as set by createSurface function-->
<div id='node_meterSelect'></div>
</div>
<div id='surfaceElement2' style='border:1px solid #ccc; width:317px; height:200px;'><!--these dimensions here in this line override the dimensions as set by createSurface function-->
<div id='node_cardSelect'></div>
</div>
</div>
<div id='paneB' class='cP_Right' data-dojo-type='dijit/layout/ContentPane'data-dojo-props='region:"center"'>
<!--<div id='surfaceElement3' style='border:1px solid #ccc;'> <!--width:520px; height:400px;'><!--it's the size-->
<!--</div>-->
</div>
</div>
...
...
...
var meter_Select = new Select
({store:memoStore1,
style:{width:'140px'},
}, "node_meterSelect");
meter_Select.startup();
on(meter_Select, 'change', function(evt)
{
console.debug('Selected Card = '+ meter_Select.value);
request.post('listofcards.php',{data:{cardX : meter_Select.value},
handleAs:"json"}).then(function(response)
...
...
The error is "
Error: Tried to register widget with id==node_meterSelect but that id is already registered"
What could be the problem? please advise.. Thanks in advance.
i found your solution. You do not map all the require values to the right variables ! So registry and combobox are not mapped right ! you map "combobox" on "on".
Take a look at this jsfiddle:
http://jsfiddle.net/ejEGr/7/
Your function head with missing parameters:
function (parser, ready, dom, domConstruct, gfx, declare,
_WidgetBase, Memory, Select, ObjectStore, request, on)
After correction:
function (parser, ready, dom, domConstruct, gfx, declare,
_WidgetBase, Memory, Select, ObjectStore, request,box,registry, on)
So i had to add box & registry and now everything should work fine.
Here is a working jsfiddle based on your code:
http://jsfiddle.net/JxpRC/2/
Maybe you used the id somewhere else in your code ?
require(["dijit/form/Select",
"dojo/data/ObjectStore",
"dojo/store/Memory","dojo/domReady!"
], function(Select, ObjectStore, Memory){
var store1 = new Memory({
data: [
{ id: "foo", label: "Foo" },
{ id: "bar", label: "Bar" }
]
});
var os = new ObjectStore({ objectStore: store1 });
var meter_Select = new Select
({store:os,
style:{width:'140px'},
}, "node_meterSelect");
meter_Select.startup();
})